forked from syndrome5/KpOpcUA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKpOpcUALogic.cs
509 lines (433 loc) · 21.7 KB
/
KpOpcUALogic.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
/*
* Made by Syndrome5 - 2018
*/
using Scada.Comm.Devices.KpOpcUA;
using System;
using System.Collections.Generic;
using System.Threading;
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Configuration;
using System.Threading.Tasks;
namespace Scada.Comm.Devices
{
public class KpOpcUALogic : KPLogic
{
private class ItemOPCUA
{
public NodeId nodeId { get; set; }
public string id { get; set; }
public MonitoringMode monMode { get; set; }
public int sampling { get; set; }
public int signal { get; set; }
public ItemOPCUA(NodeId _nodeId, string _id, MonitoringMode _monMode, int _sampling, int _signal)
{
nodeId = _nodeId;
id = _id;
monMode = _monMode;
sampling = _sampling;
signal = _signal;
}
}
private class DataItemInfo
{
public DataItemInfo()
{
Name = "";
Path = "";
KPTags = null;
}
public DataItemInfo(string name, string path)
{
Name = name;
Path = path;
KPTags = null;
}
public string Name { get; set; }
public string Path { get; set; }
public KPTag[] KPTags { get; set; }
}
private static readonly TimeSpan ReconnectSpan = TimeSpan.FromSeconds(5);
private readonly string KPNumStr;
private Config config; // конфигурация библиотеки
private bool configLoaded; // конфигурация библиотеки загружена успешно
private SortedList<string, KPTag> kpTagsByName; // список тегов КП, упорядоченный по наименованию
private bool opcUAConnected; // соединение с OPC-сервером установлено
public ApplicationConfiguration m_configuration;
public Session m_session;
public Subscription m_subscription;
public MonitoredItemNotificationEventHandler m_MonitoredItem_Notification;
public SessionReconnectHandler m_reconnectHandler;
private List<ItemOPCUA> ItemsOPCUA { get; set; }
public KpOpcUALogic(int number)
: base(number)
{
KPNumStr = Localization.UseRussian ? "КП " + number + ". " : "Device " + number + ". ";
config = new Config();
configLoaded = false;
kpTagsByName = new SortedList<string, KPTag>();
ItemsOPCUA = new List<ItemOPCUA>();
opcUAConnected = false;
// needed
CanSendCmd = true;
ConnRequired = false;
}
private static void CertificateValidator_CertificateValidation(CertificateValidator validator, CertificateValidationEventArgs e)
{
if (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted)
{
e.Accept = true;
}
}
public override void Session()
{
if (!opcUAConnected)
{
base.Session();
TimeSpan timeSpent = DateTime.Now - DateTime.MinValue;
if (timeSpent < ReconnectSpan)
Thread.Sleep(ReconnectSpan - timeSpent);
opcUAConnected = Connect().Result;
// создание подписок на чтение данных и приём событий
WorkState = opcUAConnected && CreateSubscr() ?
WorkStates.Normal : WorkStates.Error;
}
// задержка, определяемая параметрами опроса
Thread.Sleep(ReqParams.Delay);
}
public override void OnAddedToCommLine()
{
// загрузка конфигурации КП
string errMsg;
configLoaded = config.Load(Config.GetFileName(AppDirs.ConfigDir, Number), out errMsg);
int dataGroupCnt = config.DataGroups.Count;
List<TagGroup> tagGroups = new List<TagGroup>(dataGroupCnt);
int signal = 1;
if (configLoaded)
{
for (int i = 0; i < dataGroupCnt; i++) // browser folders
{
Config.DataGroup dataGroup = config.DataGroups[i];
// определение количества тегов КП в группе чтения данных
int tagCntByGroup = 0;
foreach (Config.DataItem dataItem in dataGroup.DataItems)
tagCntByGroup += 1;
// создание группы тегов КП
if (tagCntByGroup > 0)
{
TagGroup tagGroup = new TagGroup(string.IsNullOrEmpty(dataGroup.Name) ?
(Localization.UseRussian ? "Безымянная группа" : "Unnamed group") : dataGroup.Name);
int dataItemCnt = dataGroup.DataItems.Count;
List<DataItemInfo> dataGroupInfo = new List<DataItemInfo>();
dataGroup.Tag = dataGroupInfo;
for (int j = 0; j < dataItemCnt; j++) // Browse Items in a folder
{
Config.DataItem dataItem = dataGroup.DataItems[j];
string dataItemName = string.IsNullOrEmpty(dataItem.Name) ? "" : dataItem.Name;
string tagNamePrefix = dataItemName == "" ?
(Localization.UseRussian ? "Безымянный тег" : "Unnamed tag") : dataItemName;
int tagCntByItem = 1;
DataItemInfo dataItemInfo = new DataItemInfo(dataItem.Name, dataItem.Id);
dataItemInfo.KPTags = new KPTag[tagCntByItem];
//for (int k = 0; k < tagCntByItem; k++)
{
string tagName = tagNamePrefix;
KPTag kpTag = new KPTag(signal++, tagName);
tagGroup.KPTags.Add(kpTag);
dataItemInfo.KPTags[0] = kpTag; //0->k
}
if (tagCntByItem > 0 && !kpTagsByName.ContainsKey(dataItemName))
kpTagsByName.Add(dataItemName, dataItemInfo.KPTags[0]);
}
tagGroups.Add(tagGroup);
}
}
InitKPTags(tagGroups);
}
// Logs
/*
string m_UtilsLogFilePath;
bool m_deleteOnLoad = true;
int m_traceMasks = Opc.Ua.Utils.TraceMasks.Error | Opc.Ua.Utils.TraceMasks.Information;
m_UtilsLogFilePath = AppDomain.CurrentDomain.BaseDirectory + "Opc.Ua.Core.Logs.txt";
Opc.Ua.Utils.SetTraceLog(m_UtilsLogFilePath, m_deleteOnLoad);
Opc.Ua.Utils.SetTraceMask(m_traceMasks);
Opc.Ua.Utils.Trace(Opc.Ua.Utils.TraceMasks.Information, "Beginning of Opc.Ua.Core.Utils logs");
*/
WriteToLog("Configuration started");
Init().Wait();
WriteToLog("Configuration finished");
}
public async Task Init()
{
try
{
ApplicationInstance application = new ApplicationInstance
{
ApplicationType = ApplicationType.Client,
ConfigSectionName = config.ApplicationName
};
// C:\Windows\System32\file.Config.xml
m_configuration = await application.LoadApplicationConfiguration(false);
// Logs
/*
string m_UtilsLogFilePath;
bool m_deleteOnLoad = false;
int m_traceMasks = Opc.Ua.Utils.TraceMasks.Error | Opc.Ua.Utils.TraceMasks.Information;
m_UtilsLogFilePath = AppDomain.CurrentDomain.BaseDirectory + "Opc.Ua.Core.Logs.txt";
Opc.Ua.Utils.SetTraceLog(m_UtilsLogFilePath, m_deleteOnLoad);
Opc.Ua.Utils.SetTraceMask(m_traceMasks);
Opc.Ua.Utils.Trace(Opc.Ua.Utils.TraceMasks.Information, "Beginning of Opc.Ua..Utils logs");
*/
//bool appCert = await application.CheckApplicationInstanceCertificate(false, 0); E.A. не используется
m_configuration.ApplicationUri = Opc.Ua.Utils.GetApplicationUriFromCertificate(m_configuration.SecurityConfiguration.ApplicationCertificate.Certificate);
m_configuration.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation);
}
catch (Exception ex)
{
WriteToLog("Error in configuration: " + ex.Message);
}
}
private async Task<bool> Connect()
{
try
{
string path = config.ServerPath;
Boolean cert = config.UseCertificate;
var configSert = new ApplicationConfiguration()
{
ApplicationName = "ScadaCommSvc",
ApplicationUri = "urn:MAIN:OPCUA:SimulationServer",
ApplicationType = ApplicationType.Client,
SecurityConfiguration = new SecurityConfiguration
{
ApplicationCertificate = new CertificateIdentifier { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\MachineDefault", SubjectName = "CN=SimulationServer, C=FR, O= Prosys OPC, DC=MAIN" },
TrustedIssuerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Certificate Authorities" },
TrustedPeerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Applications" },
RejectedCertificateStore = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\RejectedCertificates" },
AutoAcceptUntrustedCertificates = true,
AddAppCertToTrustedStore = true
},
TransportConfigurations = new TransportConfigurationCollection(),
TransportQuotas = new TransportQuotas { OperationTimeout = 15000 },
ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 },
TraceConfiguration = new TraceConfiguration()
};
configSert.Validate(ApplicationType.Client).GetAwaiter().GetResult();
if (configSert.SecurityConfiguration.AutoAcceptUntrustedCertificates)
{
configSert.CertificateValidator.CertificateValidation += (s, e) => { e.Accept = (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted); };
}
var application = new ApplicationInstance
{
ApplicationName = "ScadaCommSvc",
ApplicationType = ApplicationType.Client,
ApplicationConfiguration = configSert
};
application.CheckApplicationInstanceCertificate(false, 2048).GetAwaiter().GetResult();
if (string.IsNullOrEmpty(path))
throw new Exception(Localization.UseRussian ? "сервер не задан" : "server is undefined");
EndpointDescription selectedEndpoint = CoreClientUtils.SelectEndpoint(path, cert, 15000);
EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(configSert/*m_configuration*/);
ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration);
m_session = await Opc.Ua.Client.Session.Create(/*m_configuration*/configSert, endpoint, false, "KpOpcUA Demo", 60000, /*new UserIdentity(new AnonymousIdentityToken())*/null, null);
m_session.KeepAlive += Client_KeepAlive;
return true;
}
catch (Exception ex)
{
WriteToLog((Localization.UseRussian ?
"Ошибка при соединении с OPC-сервером: " :
"Error connecting to OPC UA server: ") + ex.Message);
return false;
}
}
private void Client_KeepAlive(Session sender, KeepAliveEventArgs e)
{
if (e.Status != null && ServiceResult.IsNotGood(e.Status))
{
if (m_reconnectHandler == null)
{
m_reconnectHandler = new SessionReconnectHandler();
m_reconnectHandler.BeginReconnect(sender, 10000, Client_ReconnectComplete);
}
}
}
private void Client_ReconnectComplete(object sender, EventArgs e)
{
if (!Object.ReferenceEquals(sender, m_reconnectHandler))
{
return;
}
m_session = m_reconnectHandler.Session;
m_reconnectHandler.Dispose();
m_reconnectHandler = null;
}
private bool CreateSubscr()
{
try
{
foreach (Config.DataGroup dataGroup in config.DataGroups)
{
if (dataGroup.Active && dataGroup.DataItems.Count > 0)
{
if (Localization.UseRussian)
WriteToLog("Создание подписки на чтение данных" +
(string.IsNullOrEmpty(dataGroup.Name) ? "" : ". Наименование: " + dataGroup.Name));
else
WriteToLog("Create data reading subscription" +
(string.IsNullOrEmpty(dataGroup.Name) ? "" : ". Name: " + dataGroup.Name));
foreach (Config.DataItem dataItem in dataGroup.DataItems)
{
if (dataItem.Active)
{
MonitoringMode mm = new MonitoringMode();
if (dataItem.Mode == "Reporting")
mm = MonitoringMode.Reporting;
else if (dataItem.Mode == "Sampling")
mm = MonitoringMode.Sampling;
else if (dataItem.Mode == "Disabled")
mm = MonitoringMode.Disabled;
KPTag tag;
if (kpTagsByName.TryGetValue(dataItem.Name, out tag))
{
ItemsOPCUA.Add(new ItemOPCUA(null, dataItem.Id, mm, dataItem.Signal, tag.Signal-1));
}
else
{
WriteToLog("Error to assign signal to the name: " + dataItem.Name);
}
}
}
}
}
ReferenceDescriptionCollection references;
references = m_session.FetchReferences(ObjectIds.ObjectsFolder);
// parcourir
BrowseNodesId(ObjectIds.ObjectsFolder, ItemsOPCUA);
if (m_subscription != null)
{
m_subscription.ApplyChanges();
}
return true;
}
catch (Exception ex)
{
WriteToLog((Localization.UseRussian ?
"Ошибка при создании подписки на чтение данных: " :
"Error creating data reading subscription: ") + ex.Message);
return false;
}
}
private void BrowseNodesId(NodeId parent, List<ItemOPCUA> ItemsOPCUA, int maxSpace = -1, int space=0)
{
ReferenceDescriptionCollection refs;
Byte[] continuationPoint;
m_session.Browse(
null,
null,
parent,
0u,
BrowseDirection.Forward,
ReferenceTypeIds.HierarchicalReferences,
true,
(uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method,
out continuationPoint,
out refs);
if (refs.Count > 0)
{
foreach (var rd in refs)
{
bool isContinue = IfItemToSub(ref ItemsOPCUA, rd, space);
if (maxSpace != space + 1 && isContinue)
{
BrowseNodesId(ExpandedNodeId.ToNodeId(rd.NodeId, m_session.NamespaceUris), ItemsOPCUA, maxSpace, space + 1);
}
}
}
}
private bool IfItemToSub(ref List<ItemOPCUA> ItemsOPCUA, ReferenceDescription rd, int level)
{
bool continueOk = false;
foreach (var itemUA in ItemsOPCUA)
{
string[] subIds = itemUA.id.Split(new string[] { ".:." }, StringSplitOptions.None);
if (rd.DisplayName.Text == subIds[level])
{
if (subIds.Length == level + 1) // item to sub
{
ItemsOPCUA[ItemsOPCUA.IndexOf(itemUA)].nodeId = (NodeId)rd.NodeId;
CreateMonitoredItem((NodeId)rd.NodeId, Opc.Ua.Utils.Format("{0}", rd), ItemsOPCUA[ItemsOPCUA.IndexOf(itemUA)].monMode, ItemsOPCUA[ItemsOPCUA.IndexOf(itemUA)].sampling);
}
else // folder to enter
{
continueOk = true;
}
}
}
return continueOk;
}
private void OnNotification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
{
try
{
if (m_session == null)
{
return;
}
MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;
if (notification == null)
{
return;
}
foreach (var value in monitoredItem.DequeueValues())
{
foreach (var itemUA in ItemsOPCUA)
{
if (itemUA.nodeId == monitoredItem.StartNodeId)
{
double val = Convert.ToDouble(notification.Value.Value);
SetCurData(itemUA.signal, /*Convert.ToDouble(Opc.Ua.Utils.Format("{0}", notification.Value.WrappedValue))*/val, Scada.Data.Configuration.BaseValues.CnlStatuses.Defined);
break;
}
}
}
}
catch (Exception ex)
{
WriteToLog(KPNumStr + (Localization.UseRussian ?
"Ошибка при обработке изменения текущих данных: " :
"Error handling current data changing: ") + ex.Message);
lastCommSucc = false;
}
}
private void CreateMonitoredItem(NodeId nodeId, string displayName, MonitoringMode monMode, int sampling)
{
if (m_subscription == null)
{
m_subscription = new Subscription(m_session.DefaultSubscription)
{
PublishingEnabled = true,
PublishingInterval = 1000,
KeepAliveCount = 10,
LifetimeCount = 10,
MaxNotificationsPerPublish = 1000,
Priority = 100
};
m_session.AddSubscription(m_subscription);
m_subscription.Create();
}
// add the new monitored item.
MonitoredItem monitoredItem = new MonitoredItem(m_subscription.DefaultItem);
monitoredItem.StartNodeId = nodeId;
monitoredItem.AttributeId = Attributes.Value;
monitoredItem.DisplayName = displayName;
monitoredItem.MonitoringMode = monMode;
monitoredItem.SamplingInterval = sampling;
monitoredItem.QueueSize = 0;
monitoredItem.DiscardOldest = false;
monitoredItem.Notification += OnNotification;
m_subscription.AddItem(monitoredItem);
}
}
}