blob: a89553ca037579efab0d436c7ee50aa71b24b4cb [file] [log] [blame]
Constantin Ziesche181770b2020-08-20 20:32:39 +02001using BaSyx.AAS.Client.Http;
2using BaSyx.Utils.Network;
3using System;
4using System.Threading.Tasks;
5
6namespace BaSyx.Discovery.mDNS
7{
8 public static class Discovery
9 {
10 /// <summary>
11 /// Returns an AssetAdministrationShell-Http-Client if found via mDNS Discovery
12 /// </summary>
13 /// <param name="aasId">The Asset Administration Shell's unique id to look for</param>
14 /// <param name="timeout">Timeout in ms until it stops looking</param>
15 /// <returns></returns>
16 public static async Task<AssetAdministrationShellHttpClient> GetHttpClientByShellIdAsync(string aasId, int timeout)
17 {
18 AssetAdministrationShellHttpClient client = null;
19 DiscoveryServer discoveryServer = new DiscoveryServer(ServiceTypes.AAS_SERVICE_TYPE);
20
21 EventHandler<ServiceInstanceEventArgs> eventHandler = async(sender, e) =>
22 {
23 var found = e.TxtRecords.Find(f => f.Contains(aasId));
24 if (found != null)
25 foreach (var server in e.Servers)
26 {
27 bool pingable = await NetworkUtils.PingHostAsync(server.Address.ToString());
28 if (pingable)
29 {
30 var endpointRecord = e.TxtRecords.Find(f => f.Contains(server.Address.ToString()));
31 if (endpointRecord.Contains("="))
32 {
33 string[] splitted = endpointRecord.Split(new char[] { '=' }, StringSplitOptions.None);
34 Uri endpoint = new Uri(splitted[1]);
35 client = new AssetAdministrationShellHttpClient(endpoint);
36 }
37 }
38 }
39 };
40
41 discoveryServer.ServiceInstanceDiscovered += eventHandler;
42 discoveryServer.Start();
43
44 Task timeoutTask = Task.Delay(timeout);
45
46 while (client == null && !timeoutTask.IsCompleted)
47 await Task.Delay(100);
48
49 discoveryServer.ServiceInstanceDiscovered -= eventHandler;
50 discoveryServer.Stop();
51
52 return client;
53 }
54 }
55}