-
Notifications
You must be signed in to change notification settings - Fork 11
/
PublishedNodesFileHandler.cs
197 lines (176 loc) · 9.49 KB
/
PublishedNodesFileHandler.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
namespace Opc.Ua.Cloud.Publisher.Configuration
{
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Opc.Ua;
using Opc.Ua.Cloud.Publisher.Interfaces;
using Opc.Ua.Cloud.Publisher.Models;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
public class PublishedNodesFileHandler : IPublishedNodesFileHandler
{
private readonly ILogger _logger;
private readonly IUAClient _uaClient;
private readonly IUAApplication _uaApplication;
private readonly StatusHubClient _hubClient;
public PublishedNodesFileHandler(
ILoggerFactory loggerFactory,
IUAClient client,
IUAApplication uaApplication)
{
_logger = loggerFactory.CreateLogger("PublishedNodesFileHandler");
_uaClient = client;
_uaApplication = uaApplication;
_hubClient = new StatusHubClient((IHubContext<StatusHub>)Program.AppHost.Services.GetService(typeof(IHubContext<StatusHub>)));
}
private string DecryptString(string encryptedString)
{
if (!string.IsNullOrEmpty(encryptedString))
{
X509Certificate2 cert = _uaApplication.IssuerCert;
using RSA rsa = cert.GetRSAPrivateKey();
bool isBase64String = Convert.TryFromBase64String(encryptedString, new Span<byte>(new byte[encryptedString.Length]), out int bytesParsed);
if (isBase64String && (rsa != null))
{
return Encoding.UTF8.GetString(rsa.Decrypt(Convert.FromBase64String(encryptedString), RSAEncryptionPadding.Pkcs1));
}
else
{
return encryptedString;
}
}
else
{
return string.Empty;
}
}
public void ParseFile(byte[] content)
{
_logger.LogInformation($"Processing persistency file...");
List<PublishNodesInterfaceModel> _configurationFileEntries = JsonConvert.DeserializeObject<List<PublishNodesInterfaceModel>>(Encoding.UTF8.GetString(content));
// process loaded config file entries
if (_configurationFileEntries != null)
{
_logger.LogInformation($"Loaded {_configurationFileEntries.Count} config file entry/entries.");
// figure out how many nodes there are in total and capture all unique OPC UA server endpoints
Dictionary<string, PublishNodesInterfaceModel> uniqueEndpoints = new();
int totalNodeCount = 0;
foreach (PublishNodesInterfaceModel configFileEntry in _configurationFileEntries)
{
if (configFileEntry.OpcEvents != null)
{
totalNodeCount += configFileEntry.OpcEvents.Count;
}
if (configFileEntry.OpcNodes != null)
{
totalNodeCount += configFileEntry.OpcNodes.Count;
}
if (!uniqueEndpoints.ContainsKey(configFileEntry.EndpointUrl))
{
uniqueEndpoints.Add(configFileEntry.EndpointUrl, configFileEntry);
totalNodeCount++;
}
}
int currentpublishedNodeCount = 0;
if (Settings.Instance.PushCertsBeforePublishing)
{
foreach (PublishNodesInterfaceModel server in uniqueEndpoints.Values)
{
try
{
_uaClient.GDSServerPush(server.EndpointUrl, server.UserName, DecryptString(server.Password)).GetAwaiter().GetResult();
// after the cert push, give the server 5s time to become available again before trying to publish from it
Thread.Sleep(5000);
}
catch (Exception ex)
{
_logger.LogError("Cannot push new certificates to server " + server.EndpointUrl + "due to " + ex.Message);
}
currentpublishedNodeCount++;
_hubClient.UpdateClientProgressAsync(currentpublishedNodeCount * 100 / totalNodeCount).GetAwaiter().GetResult();
}
}
else
{
// make sure our progress bar is correct
currentpublishedNodeCount += uniqueEndpoints.Count;
_hubClient.UpdateClientProgressAsync(currentpublishedNodeCount * 100 / totalNodeCount).GetAwaiter().GetResult();
}
foreach (PublishNodesInterfaceModel configFileEntry in _configurationFileEntries)
{
if (configFileEntry.OpcAuthenticationMode == UserAuthModeEnum.UsernamePassword)
{
if (string.IsNullOrWhiteSpace(configFileEntry.UserName) && string.IsNullOrWhiteSpace(configFileEntry.Password))
{
throw new ArgumentException($"If {nameof(configFileEntry.OpcAuthenticationMode)} is set to '{UserAuthModeEnum.UsernamePassword}', you have to specify username and password.");
}
}
// check for events
if (configFileEntry.OpcEvents != null)
{
foreach (EventModel opcEvent in configFileEntry.OpcEvents)
{
NodePublishingModel publishingInfo = new NodePublishingModel()
{
ExpandedNodeId = ExpandedNodeId.Parse(opcEvent.ExpandedNodeId),
EndpointUrl = new Uri(configFileEntry.EndpointUrl).ToString(),
OpcAuthenticationMode = configFileEntry.OpcAuthenticationMode,
Username = configFileEntry.UserName,
Password = DecryptString(configFileEntry.Password)
};
publishingInfo.Filter = new List<FilterModel>();
publishingInfo.Filter.AddRange(opcEvent.Filter);
try
{
_uaClient.PublishNodeAsync(publishingInfo).GetAwaiter().GetResult();
}
catch (Exception ex)
{
// skip this event and log an error
_logger.LogError("Cannot publish event " + publishingInfo.ExpandedNodeId + " on server " + publishingInfo.EndpointUrl + "due to " + ex.Message);
}
currentpublishedNodeCount++;
_hubClient.UpdateClientProgressAsync(currentpublishedNodeCount * 100 / totalNodeCount).GetAwaiter().GetResult();
}
}
// check for variables
if (configFileEntry.OpcNodes != null)
{
foreach (VariableModel opcNode in configFileEntry.OpcNodes)
{
NodePublishingModel publishingInfo = new NodePublishingModel()
{
ExpandedNodeId = ExpandedNodeId.Parse(opcNode.Id),
EndpointUrl = new Uri(configFileEntry.EndpointUrl).ToString(),
OpcPublishingInterval = opcNode.OpcPublishingInterval,
OpcSamplingInterval = opcNode.OpcSamplingInterval,
HeartbeatInterval = opcNode.HeartbeatInterval,
SkipFirst = opcNode.SkipFirst,
OpcAuthenticationMode = configFileEntry.OpcAuthenticationMode,
Username = configFileEntry.UserName,
Password = DecryptString(configFileEntry.Password)
};
try
{
_uaClient.PublishNodeAsync(publishingInfo).GetAwaiter().GetResult();
}
catch (Exception ex)
{
// skip this variable and log an error
_logger.LogError("Cannot publish variable " + publishingInfo.ExpandedNodeId + " on server " + publishingInfo.EndpointUrl + "due to " + ex.Message);
}
currentpublishedNodeCount++;
_hubClient.UpdateClientProgressAsync(currentpublishedNodeCount * 100 / totalNodeCount).GetAwaiter().GetResult();
}
}
}
_logger.LogInformation("Publishednodes.json/persistency file processed successfully.");
}
}
}
}