forked from KIT-ISAS/iviz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RosClient.cs
2020 lines (1751 loc) · 76.5 KB
/
RosClient.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Iviz.Msgs;
using Iviz.MsgsGen.Dynamic;
using Iviz.Roslib.Utils;
using Iviz.Roslib.XmlRpc;
using Iviz.XmlRpc;
using Iviz.Tools;
using Nito.AsyncEx;
namespace Iviz.Roslib;
/// <summary>
/// Class that manages a client connection to a ROS master.
/// <example>
/// This initializes a ROS master:
/// <code>
/// string masterUri = "http://localhost:11311";
/// string ownId = "my_ros_id";
/// string ownUri = "http://localhost:7615";
/// var client = new RosClient(masterUri, ownId, ownUri);
/// </code>
/// </example>
/// </summary>
public sealed class RosClient : IRosClient
{
public const int AnyPort = 0;
readonly ConcurrentDictionary<string, IRosSubscriber> subscribersByTopic = new();
readonly ConcurrentDictionary<string, IRosPublisher> publishersByTopic = new();
readonly ConcurrentDictionary<string, ServiceCaller> subscribedServicesByName = new();
readonly ConcurrentDictionary<string, ServiceRequestManager> publishedServicesByName = new();
readonly string namespacePrefix;
RosNodeServer? listener;
TimeSpan tcpRosTimeout = TimeSpan.FromSeconds(3);
TimeSpan rpcNodeTimeout = TimeSpan.FromSeconds(3);
public delegate void ShutdownActionCall(string callerId, string reason);
/// <summary>
/// Handler of 'shutdown' XML-RPC calls from the slave API
/// </summary>
public ShutdownActionCall? ShutdownAction { get; set; }
public delegate void ParamUpdateActionCall(string callerId, string parameterKey, XmlRpcValue parameterValue);
/// <summary>
/// Handler of 'paramUpdate' XML-RPC calls from the slave API
/// </summary>
public ParamUpdateActionCall? ParamUpdateAction { get; set; }
/// <summary>
/// Own ID of this node.
/// </summary>
public string CallerId { get; }
/// <summary>
/// Wrapper that implements and manages XML-RPC queries to the master.
/// </summary>
public RosMasterClient RosMasterClient { get; private set; }
/// <summary>
/// Timeout in milliseconds for XML-RPC communications with the master.
/// </summary>
public TimeSpan RpcMasterTimeout
{
get => TimeSpan.FromMilliseconds(RosMasterClient.TimeoutInMs);
set
{
if (value.TotalMilliseconds <= 0)
{
BuiltIns.ThrowArgumentNull(nameof(value));
}
RosMasterClient.TimeoutInMs = (int)value.TotalMilliseconds;
}
}
/// <summary>
/// Timeout in milliseconds for XML-RPC communications with another node.
/// </summary>
public TimeSpan RpcNodeTimeout
{
get => rpcNodeTimeout;
set
{
if (value.TotalMilliseconds <= 0)
{
BuiltIns.ThrowArgumentNull(nameof(value));
}
rpcNodeTimeout = value;
}
}
/// <summary>
/// Timeout in milliseconds for TCP-ROS communications (topics, services).
/// </summary>
public TimeSpan TcpRosTimeout
{
get => tcpRosTimeout;
set
{
if (value.TotalMilliseconds <= 0)
{
BuiltIns.ThrowArgumentNull(nameof(value));
}
tcpRosTimeout = value;
int valueInMs = (int)value.TotalMilliseconds;
foreach (IRosSubscriber subscriber in subscribersByTopic.Values)
{
subscriber.TimeoutInMs = valueInMs;
}
foreach (IRosPublisher publisher in publishersByTopic.Values)
{
publisher.TimeoutInMs = valueInMs;
}
}
}
/// <summary>
/// Wrapper for XML-RPC calls to the master.
/// </summary>
public ParameterClient Parameters { get; private set; }
/// <summary>
/// URI of the master node.
/// </summary>
public Uri MasterUri => RosMasterClient.MasterUri;
/// <summary>
/// Own URI of this node.
/// </summary>
public Uri CallerUri { get; private set; }
RosClient(Uri? masterUri, string? ownId, Uri? ownUri, string? namespaceOverride)
{
masterUri ??= EnvironmentMasterUri;
if (masterUri is null)
{
throw new ArgumentException("No valid master uri provided, and ROS_MASTER_URI is not set",
nameof(masterUri));
}
if (masterUri.Scheme != "http")
{
throw new ArgumentException("URI scheme must be http", nameof(masterUri));
}
ownUri ??= TryGetCallerUriFor(masterUri) ?? TryGetCallerUri();
if (ownUri.Scheme != "http")
{
throw new ArgumentException("URI scheme must be http", nameof(ownUri));
}
if (string.IsNullOrWhiteSpace(ownId))
{
ownId = CreateCallerId();
}
string? ns = namespaceOverride ?? EnvironmentRosNamespace;
namespacePrefix = ns == null ? "/" : $"/{ns}/";
if (ownId![0] != '/')
{
ownId = $"{namespacePrefix}{ownId}";
}
if (ownId[0] == '~')
{
throw new RosInvalidResourceNameException("ROS node names may not start with a '~'");
}
ValidateResourceName(ownId);
CallerId = ownId;
CallerUri = ownUri;
RosMasterClient = new RosMasterClient(masterUri, CallerId, CallerUri, 3);
Parameters = new ParameterClient(RosMasterClient);
}
/// <summary>
/// Constructs and connects a ROS client in a sync way.
/// You should use <see cref="CreateAsync"/> in async contexts.
/// </summary>
/// <param name="masterUri">
/// URI to the master node. Example: new Uri("http://localhost:11311").
/// </param>
/// <param name="ownId">
/// The ROS name of this node.
/// This is your identity in the network, and must be unique. Example: /my_new_node
/// Leave empty to generate one automatically.
/// </param>
/// <param name="ownUri">
/// URI of this node.
/// Other clients will use this address to connect to this node.
/// Leave empty to generate one automatically. </param>
/// <param name="ensureCleanSlate">Checks if masterUri has any previous subscriptions or advertisements, and unregisters them.</param>
/// <param name="namespaceOverride">Set this to override ROS_NAMESPACE.</param>
public RosClient(Uri? masterUri = null, string? ownId = null, Uri? ownUri = null,
bool ensureCleanSlate = true, string? namespaceOverride = null) :
this(masterUri, ownId, ownUri, namespaceOverride)
{
try
{
// Do a simple ping to the master. This will tell us whether the master is reachable.
// (there is nothing special about GetUri, it's just a cheap call)
RosMasterClient.GetUri();
}
catch (Exception e) when (e is not OperationCanceledException)
{
throw new RosConnectionException($"Failed to contact the master URI at '{masterUri}'", e);
}
try
{
// Create an XmlRpc server. This will tell us quickly whether the port is taken.
listener = new RosNodeServer(this);
}
catch (SocketException e)
{
throw new RosUriBindingException($"Failed to bind to local URI '{ownUri}'", e);
}
// Start the XmlRpc server.
listener.Start();
if (CallerUri.Port == AnyPort || CallerUri.IsDefaultPort)
{
string absolutePath = Uri.UnescapeDataString(CallerUri.AbsolutePath);
CallerUri = new Uri($"http://{CallerUri.Host}:{listener.ListenerPort.ToString()}{absolutePath}");
// caller uri has changed;
RosMasterClient = new RosMasterClient(MasterUri, CallerId, CallerUri, 3);
Parameters = new ParameterClient(RosMasterClient);
}
Logger.LogDebugFormat("{0}: Initialized.", this);
if (!ensureCleanSlate)
{
return;
}
try
{
EnsureCleanSlate();
}
catch
{
Logger.LogDebugFormat("{0}: EnsureCleanState failed.", this);
listener.Dispose();
throw;
}
}
/// <summary>
/// Constructs and connects a ROS client in async.
/// </summary>
/// <param name="masterUri">
/// URI to the master node. Example: new Uri("http://localhost:11311").
/// </param>
/// <param name="ownId">
/// The ROS name of this node.
/// This is your identity in the network, and must be unique. Example: /my_new_node
/// Leave empty to generate one automatically.
/// </param>
/// <param name="ownUri">
/// URI of this node.
/// Other clients will use this address to connect to this node.
/// Leave empty to generate one automatically.
/// </param>
/// <param name="ensureCleanSlate">Checks if masterUri has any previous subscriptions or advertisements, and unregisters them.</param>
/// <param name="namespaceOverride">Set this to override ROS_NAMESPACE.</param>
/// <param name="token">An optional cancellation token.</param>
public static async ValueTask<RosClient> CreateAsync(Uri? masterUri = null, string? ownId = null,
Uri? ownUri = null, bool ensureCleanSlate = true, string? namespaceOverride = null,
CancellationToken token = default)
{
RosClient client = new(masterUri, ownId, ownUri, namespaceOverride);
try
{
// Do a simple ping to the master. This will tell us whether the master is reachable.
// (there is nothing special about GetUri, it's just a cheap call)
await client.RosMasterClient.GetUriAsync(token);
}
catch (Exception e)
{
throw new RosConnectionException($"Failed to contact the master URI '{masterUri}'", e);
}
try
{
// Create an XmlRpc server. This will tell us quickly whether the port is taken.
client.listener = new RosNodeServer(client);
}
catch (SocketException e)
{
throw new RosUriBindingException($"Failed to bind to local URI '{ownUri}'", e);
}
client.listener.Start();
if (client.CallerUri.Port == AnyPort || client.CallerUri.IsDefaultPort)
{
string absolutePath = Uri.UnescapeDataString(client.CallerUri.AbsolutePath);
client.CallerUri =
new Uri($"http://{client.CallerUri.Host}:{client.listener.ListenerPort.ToString()}{absolutePath}");
// own uri has changed;
client.RosMasterClient = new RosMasterClient(client.MasterUri, client.CallerId, client.CallerUri);
client.Parameters = new ParameterClient(client.RosMasterClient);
}
Logger.LogDebugFormat("{0}: Initialized.", client);
if (!ensureCleanSlate)
{
return client;
}
try
{
await client.EnsureCleanSlateAsync(token);
}
catch
{
Logger.LogDebugFormat("{0}: EnsureCleanState failed.", client);
await client.listener.DisposeAsync();
throw;
}
return client;
}
/// <summary>
/// Constructs and connects a ROS client. Same as calling new() directly.
/// This constructor exists only to have a sync equivalent to <see cref="CreateAsync"/> (which you should use in async contexts).
/// </summary>
/// <param name="masterUri">
/// URI to the master node. Example: new Uri("http://localhost:11311").
/// </param>
/// <param name="ownId">
/// The ROS name of this node.
/// This is your identity in the network, and must be unique. Example: /my_new_node
/// Leave empty to generate one automatically.
/// </param>
/// <param name="callerUri">
/// URI of this node.
/// Other clients will use this address to connect to this node.
/// Leave empty to generate one automatically. </param>
/// <param name="ensureCleanSlate">Checks if masterUri has any previous subscriptions or advertisements, and unregisters them.</param>
/// <param name="namespaceOverride">Set this to override ROS_NAMESPACE.</param>
public static RosClient Create(Uri? masterUri = null, string? ownId = null,
Uri? callerUri = null, bool ensureCleanSlate = true, string? namespaceOverride = null) =>
new RosClient(masterUri, ownId, callerUri, ensureCleanSlate, namespaceOverride);
/// <summary>
/// Constructs and connects a ROS client.
/// </summary>
/// <param name="masterUri">
/// URI to the master node. Example: http://localhost:11311.
/// </param>
/// <param name="ownId">
/// The ROS name of this node.
/// This is your identity in the network, and must be unique. Example: /my_new_node
/// Leave empty to generate one automatically.
/// </param>
/// <param name="ownUri">
/// URI of this node.
/// Other clients will use this address to connect to this node.
/// Leave empty to generate one automatically. </param>
/// <param name="ensureCleanSlate">Checks if masterUri has any previous subscriptions or advertisements, and unregisters them.</param>
/// <param name="namespaceOverride">Set this to override ROS_NAMESPACE.</param>
public RosClient(string? masterUri,
string? ownId = null,
string? ownUri = null,
bool ensureCleanSlate = true,
string? namespaceOverride = null) :
this(TryToCreateUri(masterUri, true), ownId, TryToCreateUri(ownUri, false), ensureCleanSlate,
namespaceOverride)
{
}
public static RosClient Create(string? masterUri, string? ownId = null,
string? ownUri = null, bool ensureCleanSlate = true, string? namespaceOverride = null) =>
new RosClient(masterUri, ownId, ownUri, ensureCleanSlate, namespaceOverride);
static Uri? TryToCreateUri(string? uri, bool isMaster)
{
if (uri == null)
{
return null;
}
if (!Uri.TryCreate(uri, UriKind.Absolute, out Uri? validatedUri))
{
throw new ArgumentException("Argument '" + uri + "' cannot be parsed as an URI. " + (isMaster
? "Try something like http://localhost:11311"
: "Try something like http://your_ip:1024, or http://your_ip:0 to use as a random port."));
}
return validatedUri;
}
/// <summary>
/// Creates a unique id based on the project and computer name
/// </summary>
/// <returns>A more or less unique id</returns>
public static string CreateCallerId()
{
string seed = EnvironmentCallerHostname + Assembly.GetCallingAssembly().GetName().Name;
return $"iviz_{seed.GetDeterministicHashCode().ToString("x8")}";
}
/// <summary>
/// Retrieves the environment variable ROS_HOSTNAME as a uri.
/// If this fails, retrieves ROS_IP.
/// </summary>
public static string? EnvironmentCallerHostname =>
Environment.GetEnvironmentVariable("ROS_HOSTNAME") ??
Environment.GetEnvironmentVariable("ROS_IP");
/// <summary>
/// Retrieves a valid caller uri for this node, by checking the local addresses
/// of the wireless and ethernet interfaces.
/// If this fails, returns a caller uri with the local hostname.
/// You should probably use <see cref="TryGetCallerUriFor"/> first and then this as a fallback.
/// </summary>
/// <param name="usingPort">Port for the caller uri, or 0 for a random free port.</param>
/// <returns>A caller uri</returns>
public static Uri TryGetCallerUri(int usingPort = AnyPort)
{
string? envHostname = EnvironmentCallerHostname;
if (envHostname != null)
{
return new Uri($"http://{envHostname}:{usingPort.ToString()}/");
}
string portStr = usingPort.ToString();
return RosUtils.GetUriFromInterface(NetworkInterfaceType.Wireless80211, portStr) ??
RosUtils.GetUriFromInterface(NetworkInterfaceType.Ethernet, portStr) ??
new Uri($"http://{Dns.GetHostName()}:{portStr}/");
}
/// <summary>
/// Tries to retrieve a valid caller uri for this node given a master address, by checking
/// the active interfaces and searching for one in the same IPv4 subnet.
/// Returns null if none is found.
/// </summary>
/// <param name="masterUri">The uri of the ROS master</param>
/// <param name="usingPort">Port for the caller uri, or 0 for a random free port.</param>
/// <returns>A caller uri, or null if none found.</returns>
public static Uri? TryGetCallerUriFor(Uri masterUri, int usingPort = AnyPort)
{
if (masterUri == null)
{
BuiltIns.ThrowArgumentNull(nameof(masterUri));
}
string? envHostname = EnvironmentCallerHostname;
if (envHostname != null)
{
return new Uri($"http://{envHostname}:{usingPort.ToString()}/");
}
var masterAddress = RosUtils.TryGetAddress(masterUri.Host);
if (masterAddress == null)
{
return null;
}
var myAddress = RosUtils.TryGetAccessibleAddress(masterAddress);
return myAddress == null ? null : new Uri($"http://{myAddress}:{usingPort.ToString()}/");
}
/// <summary>
/// Retrieves a list of possible valid caller uri with the given port.
/// Other clients will connect to this node using this address.
/// If the port is 0, uses a random free port.
/// </summary>
/// <param name="usingPort">Port for the caller uri, or 0 for a random free port.</param>
/// <returns>A list of possible caller uris.</returns>
public static Uri[] GetCallerUriCandidates(int usingPort = AnyPort)
{
var candidates = new List<Uri>();
string? envHostname = EnvironmentCallerHostname;
string portStr = usingPort.ToString();
if (envHostname != null)
{
candidates.Add(new Uri($"http://{envHostname}:{portStr}/"));
}
candidates.Add(new Uri($"http://{Dns.GetHostName()}:{portStr}/"));
var uris = RosUtils.GetAllLocalAddresses()
.Select(address => new Uri($"http://{address}:{portStr}/"));
candidates.AddRange(uris);
return candidates.ToArray();
}
/// <summary>
/// Retrieves the environment variable ROS_MASTER_URI as a uri.
/// </summary>
public static Uri? EnvironmentMasterUri
{
get
{
string? envStr = Environment.GetEnvironmentVariable("ROS_MASTER_URI");
if (envStr is null)
{
return null;
}
if (Uri.TryCreate(envStr, UriKind.Absolute, out Uri? uri))
{
return uri;
}
Logger.LogErrorFormat("EE Environment variable for master uri '{0}' is not a valid uri!", envStr);
return null;
}
}
static string? EnvironmentRosNamespace
{
get
{
string? ns = Environment.GetEnvironmentVariable("ROS_NAMESPACE");
if (string.IsNullOrEmpty(ns))
{
return null;
}
return !IsValidResourceName(ns) ? null : ns;
}
}
/// <summary>
/// Checks if the given name is a valid ROS resource name
/// </summary>
public static bool IsValidResourceName(string? name)
{
if (string.IsNullOrWhiteSpace(name))
{
return false;
}
char c0 = name[0];
if (c0 is not '/' && c0 is not '~' && !char.IsLetter(c0))
{
return false;
}
foreach (int i in 1..name.Length)
{
char c = name[i];
if (!char.IsLetterOrDigit(c) && c is not '_' && c is not '/')
{
return false;
}
}
return true;
}
/// <summary>
/// Checks if the given name is a valid ROS resource name, and throws an exception with an error message if not.
/// </summary>
public static void ValidateResourceName([NotNull] string? name)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new RosInvalidResourceNameException("Resource name is empty");
}
char c0 = name[0];
if (!char.IsLetter(c0) && c0 is not '/' && c0 is not '~')
{
throw new RosInvalidResourceNameException(
$"Resource name '{name}' is not valid. It must start with an alphanumeric character, " +
$"'/' or '~'. Current start is '{c0}'");
}
foreach (int i in 1..name.Length)
{
char c = name[i];
if (!char.IsLetterOrDigit(c) && c is not '_' && c is not '/')
{
throw new RosInvalidResourceNameException(
$"Resource name '{name}' is not valid. It must only contain alphanumeric characters, " +
$"'/' or '_'. Character at position {i} is '{c}'");
}
}
}
/// <summary>
/// Try to retrieve a valid master uri.
/// </summary>
public static Uri TryGetMasterUri()
{
return EnvironmentMasterUri ?? new Uri("http://localhost:11311/");
}
/// <summary>
/// Asks the master which topics we advertise and are subscribed to, and removes them.
/// </summary>
public void EnsureCleanSlate(CancellationToken token = default)
{
TaskUtils.Run(() => EnsureCleanSlateAsync(token).AsTask(), token).WaitAndRethrow();
}
/// <summary>
/// Asks the master which topics we advertise and are subscribed to, and removes them.
/// If you are interested in the async version, make sure to set ensureCleanSlate to false in the constructor.
/// </summary>
public async ValueTask EnsureCleanSlateAsync(CancellationToken token = default)
{
var state = await GetSystemStateAsync(token);
var tasks = new List<Task>();
tasks.AddRange(
state.Subscribers
.Where(tuple => tuple.Members.Contains(CallerId))
.Select(tuple => RosMasterClient.UnregisterSubscriberAsync(tuple.Topic, token).AsTask())
);
tasks.AddRange(
state.Publishers
.Where(tuple => tuple.Members.Contains(CallerId))
.Select(tuple => RosMasterClient.UnregisterPublisherAsync(tuple.Topic, token).AsTask()
)
);
try
{
await tasks.WhenAll();
}
catch (Exception e) when (e is not OperationCanceledException)
{
throw new RosConnectionException($"Failed to contact the master URI '{MasterUri}'", e);
}
}
/// <summary>
/// Sanity check to see if the client we just made can receive connections, or whether there is another
/// client wih the same ports interfering with ours.
/// </summary>
/// <param name="token">An optional cancellation token</param>
public void CheckOwnUri(CancellationToken token = default)
{
TaskUtils.Run(() => CheckOwnUriAsync(token).AsTask(), token).WaitAndRethrow();
}
/// <summary>
/// Sanity check to see if the client we just made can receive connections, or whether there is another
/// client wih the same ports interfering with ours.
/// </summary>
/// <param name="token">An optional cancellation token</param>
public async ValueTask CheckOwnUriAsync(CancellationToken token = default)
{
GetPidResponse response;
var ownUri = CallerUri;
try
{
response = await CreateNodeClient(ownUri).GetPidAsync(token);
}
catch (Exception e)
{
throw new RosUnreachableUriException(
$"The hostname '{ownUri.Host}' in the own uri is not reachable. " +
"Make sure that your address is correct and your node is in " +
"the correct network.", e);
}
if (!response.IsValid)
{
Logger.LogErrorFormat("{0}: Failed to validate reachability response.", this);
}
else if (response.Pid != ConnectionUtils.GetProcessId())
{
throw new RosUnreachableUriException(
$"The given own uri '{ownUri}' appears to belong to another " +
$"ROS node in the network.");
}
}
internal RosNodeClient CreateNodeClient(Uri otherUri) =>
new(CallerId, CallerUri, otherUri, (int)RpcNodeTimeout.TotalMilliseconds);
(string id, RosSubscriber<T> subscriber)
CreateSubscriber<T>(string topic, bool requestNoDelay, Action<T> firstCallback,
in T generator, RosTransportHint transportHint)
where T : IMessage
{
var topicInfo = new TopicInfo(CallerId, topic, generator);
int timeoutInMs = (int)TcpRosTimeout.TotalMilliseconds;
var subscription = new RosSubscriber<T>(this, topicInfo, requestNoDelay, timeoutInMs, transportHint);
string id = subscription.Subscribe(firstCallback);
subscribersByTopic[topic] = subscription;
var masterResponse = RosMasterClient.RegisterSubscriber(topic, topicInfo.Type);
if (!masterResponse.IsValid)
{
subscribersByTopic.TryRemove(topic, out _);
throw new RosRpcException(
$"Error registering publisher for topic {topic}: {masterResponse.StatusMessage}");
}
subscription.PublisherUpdateRcp(masterResponse.Publishers, default);
return (id, subscription);
}
async ValueTask<(string id, RosSubscriber<T> subscriber)>
CreateSubscriberAsync<T>(string topic, bool requestNoDelay, RosCallback<T> firstCallback,
T generator, RosTransportHint transportHint, CancellationToken token)
where T : IMessage
{
var topicInfo = new TopicInfo(CallerId, topic, generator);
int timeoutInMs = (int)TcpRosTimeout.TotalMilliseconds;
var subscription = new RosSubscriber<T>(this, topicInfo, requestNoDelay, timeoutInMs, transportHint);
string id = subscription.Subscribe(firstCallback);
subscribersByTopic[topic] = subscription;
RegisterSubscriberResponse masterResponse;
try
{
masterResponse = await RosMasterClient.RegisterSubscriberAsync(topic, topicInfo.Type, token);
}
catch (Exception e)
{
subscribersByTopic.TryRemove(topic, out _);
if (e is OperationCanceledException)
{
throw;
}
throw new RosRpcException($"Error registering publisher for topic {topic}", e);
}
if (!masterResponse.IsValid)
{
subscribersByTopic.TryRemove(topic, out _);
throw new RosRpcException(
$"Error registering publisher for topic {topic}: {masterResponse.StatusMessage}");
}
subscription.PublisherUpdateRcp(masterResponse.Publishers, token);
return (id, subscription);
}
/// <summary>
/// Subscribes to the given topic.
/// </summary>
/// <typeparam name="T">Message type.</typeparam>
/// <param name="topic">Name of the topic.</param>
/// <param name="callback">Function to be called when a message arrives.</param>
/// <returns>An identifier that can be used to unsubscribe from this topic.</returns>
public string Subscribe<T>(string topic, Action<T> callback)
where T : IMessage, IDeserializable<T>, new()
{
return Subscribe(topic, callback, out RosSubscriber<T> _);
}
/// <summary>
/// Subscribes to the given topic.
/// </summary>
/// <typeparam name="T">Message type.</typeparam>
/// <param name="topic">Name of the topic.</param>
/// <param name="callback">Function to be called when a message arrives.</param>
/// <param name="subscriber"> The shared subscriber for this topic, used by all subscribers from this client. </param>
/// <param name="requestNoDelay">Whether a request of NoDelay should be sent.</param>
/// <param name="transportHint">Specifies the policy of which protocol (TCP, UDP) to prefer</param>
/// <returns>An identifier that can be used to unsubscribe from this topic.</returns>
public string Subscribe<T>(string topic, Action<T> callback, out RosSubscriber<T> subscriber,
bool requestNoDelay = true, RosTransportHint transportHint = RosTransportHint.PreferTcp)
where T : IMessage, IDeserializable<T>, new()
{
if (callback is null)
{
BuiltIns.ThrowArgumentNull(nameof(callback));
}
string resolvedTopic = ResolveResourceName(topic);
if (!TryGetSubscriber(resolvedTopic, out IRosSubscriber? baseSubscriber))
{
string id;
(id, subscriber) = CreateSubscriber(resolvedTopic, requestNoDelay, callback, new T(), transportHint);
return id;
}
var newSubscriber = baseSubscriber as RosSubscriber<T>;
subscriber = newSubscriber ?? throw new RosInvalidMessageTypeException(
$"There is already a subscriber for '{topic}' with a different type [{baseSubscriber.TopicType}] - " +
$"requested type was [{BuiltIns.GetMessageType<T>()}]");
return subscriber.Subscribe(callback);
}
string IRosClient.Subscribe<T>(string topic, Action<T> callback, out IRosSubscriber<T> subscriber,
bool requestNoDelay, RosTransportHint transportHint)
{
string id = Subscribe(topic, callback, out RosSubscriber<T> newSubscriber, requestNoDelay, transportHint);
subscriber = newSubscriber;
return id;
}
/// <summary>
/// Subscribes to the given topic. The subscriber will try to reconstruct the message based on information
/// transmitted during handshake. The message type will be <see cref="DynamicMessage"/> if the message type is not known.
/// </summary>
/// <param name="topic">Name of the topic.</param>
/// <param name="callback">Function to be called when a message arrives.</param>
/// <param name="subscriber"> The shared subscriber for this topic, used by all subscribers from this client. </param>
/// <param name="requestNoDelay">Whether a request of NoDelay should be sent.</param>
/// <param name="transportHint">Specifies the policy of which protocol (TCP, UDP) to prefer</param>
/// <returns>A pair containing an identifier that can be used to unsubscribe from this topic, and the subscriber object.</returns>
public string Subscribe(string topic, Action<IMessage> callback, out RosSubscriber<IMessage> subscriber,
bool requestNoDelay = true, RosTransportHint transportHint = RosTransportHint.PreferTcp)
{
if (callback is null)
{
BuiltIns.ThrowArgumentNull(nameof(callback));
}
string resolvedTopic = ResolveResourceName(topic);
if (!TryGetSubscriber(resolvedTopic, out IRosSubscriber? baseSubscriber))
{
string id;
(id, subscriber) =
CreateSubscriber(resolvedTopic, requestNoDelay, callback, new DynamicMessage(), transportHint);
return id;
}
var newSubscriber = baseSubscriber as RosSubscriber<IMessage>;
subscriber = newSubscriber ?? throw new RosInvalidMessageTypeException(
$"There is already a subscriber for '{topic}' with a different type [{baseSubscriber.TopicType}] - " +
$"requested type was [IMessage](generic)");
return subscriber.Subscribe(callback);
}
string IRosClient.Subscribe(string topic, Action<IMessage> callback, out IRosSubscriber subscriber,
bool requestNoDelay, RosTransportHint transportHint)
{
string id = Subscribe(topic, callback, out RosSubscriber<IMessage> newSubscriber, requestNoDelay,
transportHint);
subscriber = newSubscriber;
return id;
}
/// <summary>
/// Subscribes to the given topic.
/// </summary>
/// <typeparam name="T">Message type.</typeparam>
/// <param name="topic">Name of the topic.</param>
/// <param name="callback">Function to be called when a message arrives.</param>
/// <param name="requestNoDelay">Whether a request of NoDelay should be sent.</param>
/// <param name="transportHint">Specifies the policy of which protocol (TCP, UDP) to prefer</param>
/// <param name="token">An optional cancellation token</param>
/// <returns>A pair containing an identifier that can be used to unsubscribe from this topic, and the subscriber object.</returns>
public ValueTask<(string id, RosSubscriber<T> subscriber)> SubscribeAsync<T>(
string topic, Action<T> callback, bool requestNoDelay = true,
RosTransportHint transportHint = RosTransportHint.PreferTcp, CancellationToken token = default)
where T : IMessage, IDeserializable<T>, new()
{
void Callback(in T t, IRosReceiver _) => callback(t);
return SubscribeAsync(topic, (RosCallback<T>)Callback, requestNoDelay, transportHint, token);
}
async ValueTask<(string id, IRosSubscriber<T> subscriber)> IRosClient.SubscribeAsync<T>(
string topic, Action<T> callback, bool requestNoDelay,
RosTransportHint transportHint, CancellationToken token)
{
return await SubscribeAsync(topic, callback, requestNoDelay, transportHint, token);
}
/// <summary>
/// Subscribes to the given topic. The subscriber will try to reconstruct the message based on information
/// transmitted during handshake. The message type will be <see cref="DynamicMessage"/> if the message type is not known.
/// </summary>
/// <param name="topic">Name of the topic.</param>
/// <param name="callback">Function to be called when a message arrives.</param>
/// <param name="requestNoDelay">Whether a request of NoDelay should be sent.</param>
/// <param name="transportHint">Specifies the policy of which protocol (TCP, UDP) to prefer</param>
/// <param name="token">An optional cancellation token</param>
/// <returns>A pair containing an identifier that can be used to unsubscribe from this topic, and the subscriber object.</returns>
public ValueTask<(string id, RosSubscriber<IMessage> subscriber)> SubscribeAsync(
string topic, Action<IMessage> callback, bool requestNoDelay = true,
RosTransportHint transportHint = RosTransportHint.PreferTcp, CancellationToken token = default)
{
if (callback is null)
{
BuiltIns.ThrowArgumentNull(nameof(callback));
}
string resolvedTopic = ResolveResourceName(topic);
if (!TryGetSubscriberImpl(resolvedTopic, out IRosSubscriber? existingSubscriber))
{
void Callback(in IMessage t, IRosReceiver _) => callback(t);
return CreateSubscriberAsync(resolvedTopic, requestNoDelay, (RosCallback<IMessage>)Callback,
new DynamicMessage(), transportHint, token);
}
if (existingSubscriber is not RosSubscriber<IMessage> validatedSubscriber)
{
throw new RosInvalidMessageTypeException(
$"There is already a subscriber for '{topic}' with a different type [{existingSubscriber.TopicType}] - " +
$"requested type was [IMessage](generic)");
}
return (validatedSubscriber.Subscribe(callback), subscriber: validatedSubscriber).AsTaskResult();
}
async ValueTask<(string id, IRosSubscriber subscriber)> IRosClient.SubscribeAsync(
string topic, Action<IMessage> callback, bool requestNoDelay, RosTransportHint transportHint,
CancellationToken token)
{
return await SubscribeAsync(topic, callback, requestNoDelay, transportHint, token);
}
/// <summary>
/// Subscribes to the given topic. This variant uses a callback that includes information about
/// the receiver socket and who sent the message.
/// </summary>
/// <typeparam name="T">Message type.</typeparam>
/// <param name="topic">Name of the topic.</param>
/// <param name="callback">Function to be called when a message arrives.</param>
/// <param name="requestNoDelay">Whether a request of NoDelay should be sent.</param>
/// <param name="transportHint">Specifies the policy of which protocol (TCP, UDP) to prefer</param>
/// <param name="token">An optional cancellation token</param>
/// <returns>A pair containing an identifier that can be used to unsubscribe from this topic, and the subscriber object.</returns>
public ValueTask<(string id, RosSubscriber<T> subscriber)> SubscribeAsync<T>(
string topic, RosCallback<T> callback, bool requestNoDelay = true,
RosTransportHint transportHint = RosTransportHint.PreferTcp, CancellationToken token = default)
where T : IMessage, IDeserializable<T>, new()
{
if (callback is null)
{
BuiltIns.ThrowArgumentNull(nameof(callback));
}
string resolvedTopic = ResolveResourceName(topic);
if (!TryGetSubscriberImpl(resolvedTopic, out IRosSubscriber? existingSubscriber))
{
return CreateSubscriberAsync(resolvedTopic, requestNoDelay, callback, new T(), transportHint, token);
}
if (existingSubscriber is not RosSubscriber<T> validatedSubscriber)
{
throw new RosInvalidMessageTypeException(
$"There is already a subscriber for '{topic}' with a different type [{existingSubscriber.TopicType}] - " +
$"requested type was [{BuiltIns.GetMessageType<T>()}]");
}
return (validatedSubscriber.Subscribe(callback), validatedSubscriber).AsTaskResult();
}
async ValueTask<(string id, IRosSubscriber<T> subscriber)> IRosClient.SubscribeAsync<T>(
string topic, RosCallback<T> callback, bool requestNoDelay,
RosTransportHint transportHint, CancellationToken token)
{
return await SubscribeAsync(topic, callback, requestNoDelay, transportHint, token);
}
/// <summary>
/// Unsubscribe from the given topic.
/// </summary>
/// <param name="topicId">Token returned by Subscribe().</param>
/// <returns>Whether the unsubscription succeeded.</returns>
public bool Unsubscribe(string topicId)