forked from barnstee/UA-CloudPublisher
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPublishedNodesFileHandler.cs
More file actions
207 lines (185 loc) · 9.42 KB
/
Copy pathPublishedNodesFileHandler.cs
File metadata and controls
207 lines (185 loc) · 9.42 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
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
namespace Opc.Ua.Cloud.Publisher.Configuration
{
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;
using System.Threading.Tasks;
public class PublishedNodesFileHandler : IPublishedNodesFileHandler
{
private readonly ILogger _logger;
private readonly IUAClient _uaClient;
private readonly IUAApplication _uaApplication;
public int Progress { get; set; } = 0;
public PublishedNodesFileHandler(
ILoggerFactory loggerFactory,
IUAClient client,
IUAApplication uaApplication)
{
_logger = loggerFactory.CreateLogger("PublishedNodesFileHandler");
_uaClient = client;
_uaApplication = uaApplication;
}
private string DecryptString(string encryptedString)
{
if (!string.IsNullOrEmpty(encryptedString))
{
X509Certificate2 cert = _uaApplication.IssuerCert;
if (cert == null)
{
return encryptedString;
}
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 async Task ParseFileAsync(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
{
await _uaClient.GDSServerPushAsync(server.EndpointUrl, server.UserName, DecryptString(server.Password)).ConfigureAwait(false);
// after the cert push, give the server 5s time to become available again before trying to publish from it
await Task.Delay(5000).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError("Cannot push new certificates to server " + server.EndpointUrl + "due to " + ex.Message);
}
currentpublishedNodeCount++;
Progress = currentpublishedNodeCount * 100 / totalNodeCount;
}
}
else
{
// make sure our progress bar is correct
currentpublishedNodeCount += uniqueEndpoints.Count;
if (totalNodeCount > 0)
{
Progress = currentpublishedNodeCount * 100 / totalNodeCount;
}
else
{
Progress = 0;
}
}
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),
Filter = [.. opcEvent.Filter]
};
try
{
await _uaClient.PublishNodeAsync(publishingInfo).ConfigureAwait(false);
}
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++;
Progress = currentpublishedNodeCount * 100 / totalNodeCount;
}
}
// 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
{
await _uaClient.PublishNodeAsync(publishingInfo).ConfigureAwait(false);
}
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++;
Progress = currentpublishedNodeCount * 100 / totalNodeCount;
}
}
}
_logger.LogInformation("Publishednodes.json/persistency file processed successfully.");
}
}
}
}