-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathUANodeManager.cs
1847 lines (1597 loc) · 76.1 KB
/
UANodeManager.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
namespace Opc.Ua.Edge.Translator
{
using Newtonsoft.Json;
using Opc.Ua;
using Opc.Ua.Edge.Translator.Interfaces;
using Opc.Ua.Edge.Translator.Models;
using Opc.Ua.Server;
using Serilog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UANodeSet = Export.UANodeSet;
public class UANodeManager : CustomNodeManager2
{
private long _lastUsedId = 0;
private bool _shutdown = false;
private readonly UAModel.WoT_Con.WoTAssetConnectionManagementTypeState _assetManagement = new(null);
private readonly Dictionary<string, BaseDataVariableState> _uaVariables = new();
private readonly Dictionary<string, IAsset> _assets = new();
private readonly Dictionary<string, List<AssetTag>> _tags = new();
private readonly UACloudLibraryClient _uacloudLibraryClient = new();
private readonly Dictionary<NodeId, FileManager> _fileManagers = new();
private uint _ticks = 0;
public UANodeManager(IServerInternal server, ApplicationConfiguration configuration)
: base(server, configuration)
{
SystemContext.NodeIdFactory = this;
// create our settings folder, if required
if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "settings")))
{
Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "settings"));
}
// in the node manager constructor, we add all namespaces
List<string> namespaceUris = new()
{
"http://opcfoundation.org/UA/EdgeTranslator/"
};
// log into UA Cloud Library and download available namespaces
_uacloudLibraryClient.Login(Environment.GetEnvironmentVariable("UACLURL"), Environment.GetEnvironmentVariable("UACLUsername"), Environment.GetEnvironmentVariable("UACLPassword"));
LoadNamespaceUrisFromNodesetXml(namespaceUris, "Opc.Ua.WotCon.NodeSet2.xml");
// add a seperate namespace for each asset from the WoT TD files
IEnumerable<string> WoTFiles = Directory.EnumerateFiles(Path.Combine(Directory.GetCurrentDirectory(), "settings"), "*.jsonld");
foreach (string file in WoTFiles)
{
try
{
string contents = File.ReadAllText(file);
// parse WoT TD file contents
ThingDescription td = JsonConvert.DeserializeObject<ThingDescription>(contents);
namespaceUris.Add("http://opcfoundation.org/UA/" + td.Name + "/");
AddNamespacesFromCompanionSpecs(namespaceUris, td);
}
catch (Exception ex)
{
// skip this file, but log an error
Log.Logger.Error(ex.Message, ex);
}
}
NamespaceUris = namespaceUris;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
lock (Lock)
{
foreach (FileManager manager in _fileManagers.Values)
{
manager.Dispose();
}
_fileManagers.Clear();
}
}
}
public override NodeId New(ISystemContext context, NodeState node)
{
// for new nodes we create, pick our default namespace
return new NodeId(Utils.IncrementIdentifier(ref _lastUsedId), (ushort)Server.NamespaceUris.GetIndex("http://opcfoundation.org/UA/EdgeTranslator/"));
}
public void HandleServerRestart()
{
_shutdown = true;
Program.App.Stop();
Program.App.Start(new UAServer()).GetAwaiter().GetResult();
}
public override void CreateAddressSpace(IDictionary<NodeId, IList<IReference>> externalReferences)
{
lock (Lock)
{
// in the create address space call, we add all our nodes
IList<IReference> objectsFolderReferences = null;
if (!externalReferences.TryGetValue(Ua.ObjectIds.ObjectsFolder, out objectsFolderReferences))
{
externalReferences[Ua.ObjectIds.ObjectsFolder] = objectsFolderReferences = new List<IReference>();
}
AddNodesFromNodesetXml("Opc.Ua.WotCon.NodeSet2.xml");
AddNodesForAssetManagement(objectsFolderReferences);
IEnumerable<string> WoTFiles = Directory.EnumerateFiles(Path.Combine(Directory.GetCurrentDirectory(), "settings"), "*.jsonld");
foreach (string file in WoTFiles)
{
try
{
string contents = File.ReadAllText(file);
string fileName = Path.GetFileNameWithoutExtension(file);
if (!CreateAssetNode(fileName, out NodeState assetNode))
{
throw new Exception("Asset already exists");
}
AddNodesForWoTProperties(assetNode, contents);
}
catch (Exception ex)
{
// skip this file, but log an error
Log.Logger.Error(ex.Message, ex);
}
}
AddReverseReferences(externalReferences);
base.CreateAddressSpace(externalReferences);
}
}
private void AddNodesForAssetManagement(IList<IReference> objectsFolderReferences)
{
ushort WoTConNamespaceIndex = (ushort)Server.NamespaceUris.GetIndex(UAModel.WoT_Con.Namespaces.WoT_Con);
BaseObjectState assetManagementPassiveNode = (BaseObjectState)FindPredefinedNode(new NodeId(UAModel.WoT_Con.Objects.WoTAssetConnectionManagement, WoTConNamespaceIndex), typeof(BaseObjectState));
_assetManagement.Create(SystemContext, assetManagementPassiveNode);
MethodState createAssetPassiveNode = (MethodState)FindPredefinedNode(new NodeId(UAModel.WoT_Con.Methods.WoTAssetConnectionManagement_CreateAsset, WoTConNamespaceIndex), typeof(MethodState));
_assetManagement.CreateAsset = new(null);
_assetManagement.CreateAsset.Create(SystemContext, createAssetPassiveNode);
_assetManagement.CreateAsset.OnCall = new UAModel.WoT_Con.CreateAssetMethodStateMethodCallHandler(OnCreateAsset);
BaseVariableState createAssetInputArgumentsPassiveNode = (BaseVariableState)FindPredefinedNode(new NodeId(UAModel.WoT_Con.Variables.WoTAssetConnectionManagementType_CreateAsset_InputArguments, WoTConNamespaceIndex), typeof(BaseVariableState));
_assetManagement.CreateAsset.InputArguments = new(null);
_assetManagement.CreateAsset.InputArguments.Create(SystemContext, createAssetInputArgumentsPassiveNode);
BaseVariableState createAssetOutputArgumentsPassiveNode = (BaseVariableState)FindPredefinedNode(new NodeId(UAModel.WoT_Con.Variables.WoTAssetConnectionManagementType_CreateAsset_OutputArguments, WoTConNamespaceIndex), typeof(BaseVariableState));
_assetManagement.CreateAsset.OutputArguments = new(null);
_assetManagement.CreateAsset.OutputArguments.Create(SystemContext, createAssetOutputArgumentsPassiveNode);
MethodState deleteAssetPassiveNode = (MethodState)FindPredefinedNode(new NodeId(UAModel.WoT_Con.Methods.WoTAssetConnectionManagement_DeleteAsset, WoTConNamespaceIndex), typeof(MethodState));
_assetManagement.DeleteAsset = new(null);
_assetManagement.DeleteAsset.Create(SystemContext, deleteAssetPassiveNode);
_assetManagement.DeleteAsset.OnCall = new UAModel.WoT_Con.DeleteAssetMethodStateMethodCallHandler(OnDeleteAsset);
BaseVariableState deleteAssetInputArgumentsPassiveNode = (BaseVariableState)FindPredefinedNode(new NodeId(UAModel.WoT_Con.Variables.WoTAssetConnectionManagementType_DeleteAsset_InputArguments, WoTConNamespaceIndex), typeof(BaseVariableState));
_assetManagement.DeleteAsset.InputArguments = new(null);
_assetManagement.DeleteAsset.InputArguments.Create(SystemContext, deleteAssetInputArgumentsPassiveNode);
// create a variable listing our supported WoT protocol bindings
_uaVariables.Add("SupportedWoTBindings", CreateVariable(_assetManagement, "SupportedWoTBindings", new ExpandedNodeId(DataTypes.UriString), WoTConNamespaceIndex, false, new string[7] {
"https://www.w3.org/2019/wot/modbus",
"https://www.w3.org/2019/wot/opcua",
"https://www.w3.org/2019/wot/s7",
"https://www.w3.org/2019/wot/mcp",
"https://www.w3.org/2019/wot/eip",
"https://www.w3.org/2019/wot/ads",
"http://www.w3.org/2022/bacnet"
}));
// add everything to our server namespace
objectsFolderReferences.Add(new NodeStateReference(ReferenceTypes.Organizes, false, _assetManagement.NodeId));
AddPredefinedNode(SystemContext, _assetManagement);
}
private void AddNamespacesFromCompanionSpecs(List<string> namespaceUris, ThingDescription td)
{
// check if an OPC UA companion spec is mentioned in the WoT TD file
foreach (object ns in td.Context)
{
if (ns.ToString().Contains("https://www.w3.org/") && !ns.ToString().Contains("opcua"))
{
continue;
}
OpcUaNamespaces namespaces = JsonConvert.DeserializeObject<OpcUaNamespaces>(ns.ToString());
if (namespaces.Namespaces != null)
{
foreach (Uri opcuaCompanionSpecUrl in namespaces.Namespaces)
{
// support local Nodesets
if (!opcuaCompanionSpecUrl.IsAbsoluteUri || (!opcuaCompanionSpecUrl.AbsoluteUri.Contains("http://") && !opcuaCompanionSpecUrl.AbsoluteUri.Contains("https://")))
{
string nodesetFile = string.Empty;
if (Path.IsPathFullyQualified(opcuaCompanionSpecUrl.OriginalString))
{
// absolute file path
nodesetFile = opcuaCompanionSpecUrl.OriginalString;
}
else
{
// relative file path
nodesetFile = Path.Combine(Directory.GetCurrentDirectory(), opcuaCompanionSpecUrl.OriginalString);
}
Log.Logger.Information("Loading nodeset from local file: " + nodesetFile);
LoadNamespaceUrisFromNodesetXml(namespaceUris, nodesetFile);
}
else
{
if (_uacloudLibraryClient.DownloadNamespace(Environment.GetEnvironmentVariable("UACLURL"), opcuaCompanionSpecUrl.OriginalString))
{
Log.Logger.Information("Loaded nodeset from Cloud Library URL: " + opcuaCompanionSpecUrl);
foreach (string nodesetFile in _uacloudLibraryClient._nodeSetFilenames)
{
LoadNamespaceUrisFromNodesetXml(namespaceUris, nodesetFile);
}
}
else
{
Log.Logger.Warning($"Could not load nodeset {opcuaCompanionSpecUrl.OriginalString}");
}
}
}
}
string validationError = _uacloudLibraryClient.ValidateNamespacesAndModels(Environment.GetEnvironmentVariable("UACLURL"), true);
if (!string.IsNullOrEmpty(validationError))
{
Log.Logger.Error(validationError);
}
}
}
private void AddNodesFromCompanionSpecs(ThingDescription td)
{
// we need as many passes as we have nodesetfiles to make sure all references can be resolved
for (int i = 0; i < _uacloudLibraryClient._nodeSetFilenames.Count; i++)
{
foreach (string nodesetFile in _uacloudLibraryClient._nodeSetFilenames)
{
AddNodesFromNodesetXml(nodesetFile);
}
}
foreach (object ns in td.Context)
{
if (ns.ToString().Contains("https://www.w3.org/") && !ns.ToString().Contains("opcua"))
{
continue;
}
OpcUaNamespaces namespaces = JsonConvert.DeserializeObject<OpcUaNamespaces>(ns.ToString());
if (namespaces.Namespaces != null)
{
foreach (Uri opcuaCompanionSpecUrl in namespaces.Namespaces)
{
// support local Nodesets
if (!opcuaCompanionSpecUrl.IsAbsoluteUri || (!opcuaCompanionSpecUrl.AbsoluteUri.Contains("http://") && !opcuaCompanionSpecUrl.AbsoluteUri.Contains("https://")))
{
string nodesetFile = string.Empty;
if (Path.IsPathFullyQualified(opcuaCompanionSpecUrl.OriginalString))
{
// absolute file path
nodesetFile = opcuaCompanionSpecUrl.OriginalString;
}
else
{
// relative file path
nodesetFile = Path.Combine(Directory.GetCurrentDirectory(), opcuaCompanionSpecUrl.OriginalString);
}
Log.Logger.Information("Adding node set from local nodeset file");
AddNodesFromNodesetXml(nodesetFile);
}
}
}
}
}
private void LoadNamespaceUrisFromNodesetXml(List<string> namespaceUris, string nodesetFile)
{
using (FileStream stream = new(nodesetFile, FileMode.Open, FileAccess.Read))
{
UANodeSet nodeSet = UANodeSet.Read(stream);
if ((nodeSet.NamespaceUris != null) && (nodeSet.NamespaceUris.Length > 0))
{
foreach (string ns in nodeSet.NamespaceUris)
{
if (!namespaceUris.Contains(ns))
{
namespaceUris.Add(ns);
}
}
}
}
}
private void AddNodesFromNodesetXml(string nodesetFile)
{
using (Stream stream = new FileStream(nodesetFile, FileMode.Open))
{
UANodeSet nodeSet = UANodeSet.Read(stream);
NodeStateCollection predefinedNodes = new NodeStateCollection();
nodeSet.Import(SystemContext, predefinedNodes);
for (int i = 0; i < predefinedNodes.Count; i++)
{
try
{
AddPredefinedNode(SystemContext, predefinedNodes[i]);
}
catch (Exception ex)
{
Log.Logger.Error(ex.Message, ex);
}
}
}
}
public override void DeleteAddressSpace()
{
lock (Lock)
{
base.DeleteAddressSpace();
}
}
private ServiceResult OnCreateAsset(
ISystemContext _context,
MethodState _method,
NodeId _objectId,
string assetName,
ref NodeId assetId)
{
if (string.IsNullOrEmpty(assetName))
{
return StatusCodes.BadInvalidArgument;
}
bool success = CreateAssetNode(assetName, out NodeState assetNode);
if (!success)
{
return new ServiceResult(StatusCodes.BadBrowseNameDuplicated, new Ua.LocalizedText(assetNode.NodeId.ToString()));
}
else
{
assetId = assetNode.NodeId;
return ServiceResult.Good;
}
}
private bool CreateAssetNode(string assetName, out NodeState assetNode)
{
lock (Lock)
{
// check if the asset node already exists
INodeBrowser browser = _assetManagement.CreateBrowser(
SystemContext,
null,
null,
false,
BrowseDirection.Forward,
null,
null,
true);
IReference reference = browser.Next();
while ((reference != null) && (reference is NodeStateReference))
{
NodeStateReference node = reference as NodeStateReference;
if ((node.Target != null) && (node.Target.DisplayName.Text == assetName))
{
assetNode = node.Target;
return false;
}
reference = browser.Next();
}
UAModel.WoT_Con.IWoTAssetTypeState asset = new(null);
asset.Create(SystemContext, new NodeId(), new QualifiedName(assetName), null, true);
_assetManagement.AddChild(asset);
FileManager fileManager = new(this, asset.WoTFile);
_fileManagers.Add(asset.NodeId, fileManager);
AddPredefinedNode(SystemContext, asset);
assetNode = asset;
return true;
}
}
private ServiceResult OnDeleteAsset(
ISystemContext _context,
MethodState _method,
NodeId _objectId,
NodeId assetId)
{
lock (Lock)
{
NodeState asset = FindPredefinedNode(assetId, typeof(UAModel.WoT_Con.IWoTAssetTypeState));
if (asset == null)
{
return StatusCodes.BadNodeIdUnknown;
}
string assetName = asset.DisplayName.Text;
_fileManagers.Remove(assetId);
DeleteNode(SystemContext, assetId);
IEnumerable<string> WoTFiles = Directory.EnumerateFiles(Path.Combine(Directory.GetCurrentDirectory(), "settings"), "*.jsonld");
foreach (string file in WoTFiles)
{
string fileName = Path.GetFileNameWithoutExtension(file);
if (fileName == assetName)
{
File.Delete(file);
}
}
if (_tags.ContainsKey(assetName))
{
_tags.Remove(assetName);
}
if (_assets.ContainsKey(assetName))
{
_assets.Remove(assetName);
}
int i = 0;
while (i < _uaVariables.Count)
{
if (_uaVariables.Keys.ToArray()[i].StartsWith(assetName + ":"))
{
_uaVariables.Remove(_uaVariables.Keys.ToArray()[i]);
}
else
{
i++;
}
}
return ServiceResult.Good;
}
}
public void AddNodesForWoTProperties(NodeState parent, string contents)
{
// parse WoT TD file contents
ThingDescription td = JsonConvert.DeserializeObject<ThingDescription>(contents);
string newNamespace = "http://opcfoundation.org/UA/" + td.Name + "/";
List<string> namespaceUris = new(NamespaceUris);
if (!namespaceUris.Contains(newNamespace))
{
namespaceUris.Add(newNamespace);
};
foreach (object ns in td.Context)
{
if (!ns.ToString().Contains("https://www.w3.org/") && ns.ToString().Contains("opcua"))
{
OpcUaNamespaces namespaces = JsonConvert.DeserializeObject<OpcUaNamespaces>(ns.ToString());
foreach (Uri opcuaCompanionSpecUrl in namespaces.Namespaces)
{
namespaceUris.Add(opcuaCompanionSpecUrl.ToString());
}
}
}
AddNamespacesFromCompanionSpecs(namespaceUris, td);
NamespaceUris = namespaceUris;
AddNodesFromCompanionSpecs(td);
byte unitId = 1;
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DISABLE_ASSET_CONNECTION_TEST")))
{
AssetConnectionTest(td, out unitId);
}
// create nodes for each TD property
foreach (KeyValuePair<string, Property> property in td.Properties)
{
foreach (object form in property.Value.Forms)
{
AddNodeForWoTForm(parent, td, property, form, td.Name, unitId);
}
}
_ = Task.Factory.StartNew(UpdateNodeValues, td.Name, TaskCreationOptions.LongRunning);
Log.Logger.Information($"Successfully parsed WoT file for asset: {td.Name}");
}
private void AddNodeForWoTForm(NodeState assetFolder, ThingDescription td, KeyValuePair<string, Property> property, object form, string assetId, byte unitId)
{
string variableId;
string variableName;
if (string.IsNullOrEmpty(property.Value.OpcUaNodeId))
{
variableId = $"{assetId}:{property.Key}";
variableName = property.Key;
}
else
{
variableId = $"{assetId}:{property.Value.OpcUaNodeId}";
variableName = property.Value.OpcUaNodeId.Substring(property.Value.OpcUaNodeId.IndexOf("=") + 1);
}
string fieldPath = string.Empty;
// create an OPC UA variable optionally with a specified type.
if (!string.IsNullOrEmpty(property.Value.OpcUaType))
{
string[] opcuaTypeParts = property.Value.OpcUaType.Split(new char[] { '=', ';' });
if ((opcuaTypeParts.Length > 3) && (opcuaTypeParts[0] == "nsu") && (opcuaTypeParts[2] == "i"))
{
string namespaceURI = opcuaTypeParts[1];
uint nodeID = uint.Parse(opcuaTypeParts[3]);
if (NamespaceUris.Contains(namespaceURI))
{
// check if this variable is part of a complex type and we need to load the complex type first and then assign a part of it to the new variable.
if (!string.IsNullOrEmpty(property.Value.OpcUaFieldPath))
{
DataTypeState opcuaType = (DataTypeState)Find(ExpandedNodeId.ToNodeId(ParseExpandedNodeId(property.Value.OpcUaType), Server.NamespaceUris));
if ((opcuaType?.DataTypeDefinition?.Body is StructureDefinition) && (((StructureDefinition)opcuaType?.DataTypeDefinition?.Body)?.Fields?.Count > 0))
{
ExtensionObject complexTypeInstance = new()
{
TypeId = opcuaType.NodeId
};
BinaryEncoder encoder = new(ServiceMessageContext.GlobalContext);
foreach (StructureField field in ((StructureDefinition)opcuaType?.DataTypeDefinition?.Body).Fields)
{
// check which built-in type the complex type field is. See https://reference.opcfoundation.org/Core/Part6/v104/docs/5.1.2
switch (field.DataType.ToString())
{
case "i=10": encoder.WriteFloat(field.Name, 0); break;
case "i=1": encoder.WriteBoolean(field.Name, false); break;
case "i=6": encoder.WriteInt32(field.Name, 0); break;
case "i=12": encoder.WriteString(field.Name, string.Empty); break;
default: throw new NotImplementedException("Complex type field data type " + field.DataType.ToString() + " not yet supported!");
}
if (field.Name == property.Value.OpcUaFieldPath)
{
// add the field path to make sure we can distinguish the tag during data updates
fieldPath = field.Name;
}
}
complexTypeInstance.Body = encoder.CloseAndReturnBuffer();
// now add it, if it doesn't already exist
if (!_uaVariables.ContainsKey(variableId))
{
_uaVariables.Add(variableId, CreateVariable(assetFolder, variableName, new ExpandedNodeId(new NodeId(nodeID), namespaceURI), assetFolder.NodeId.NamespaceIndex, !property.Value.ReadOnly, complexTypeInstance));
}
}
else
{
// OPC UA type info not found, default to float
_uaVariables.Add(variableId, CreateVariable(assetFolder, variableName, new ExpandedNodeId(DataTypes.Float), assetFolder.NodeId.NamespaceIndex, !property.Value.ReadOnly));
}
}
else
{
// it's an OPC UA built-in type
_uaVariables.Add(variableId, CreateVariable(assetFolder, variableName, new ExpandedNodeId(new NodeId(nodeID), namespaceURI), assetFolder.NodeId.NamespaceIndex, !property.Value.ReadOnly));
}
}
else
{
// no namespace info, default to float
_uaVariables.Add(variableId, CreateVariable(assetFolder, variableName, new ExpandedNodeId(DataTypes.Float), assetFolder.NodeId.NamespaceIndex, !property.Value.ReadOnly));
}
}
else
{
// can't parse type info, default to float
_uaVariables.Add(variableId, CreateVariable(assetFolder, variableName, new ExpandedNodeId(DataTypes.Float), assetFolder.NodeId.NamespaceIndex, !property.Value.ReadOnly));
}
}
else
{
// no type info, default to float
_uaVariables.Add(variableId, CreateVariable(assetFolder, variableName, new ExpandedNodeId(DataTypes.Float), assetFolder.NodeId.NamespaceIndex, !property.Value.ReadOnly));
}
// check if we need to create a new asset first
if (!_tags.ContainsKey(assetId))
{
_tags.Add(assetId, new List<AssetTag>());
}
AddTag(td, form, assetId, unitId, variableId, fieldPath);
}
private void AddTag(ThingDescription td, object form, string assetId, byte unitId, string variableId, string fieldPath)
{
if (td.Base.ToLower().StartsWith("modbus+tcp://"))
{
// create an asset tag and add to our list
ModbusForm modbusForm = JsonConvert.DeserializeObject<ModbusForm>(form.ToString());
AssetTag tag = new()
{
Name = variableId,
Address = modbusForm.Href,
UnitID = unitId,
Type = modbusForm.ModbusType.ToString(),
PollingInterval = (int)modbusForm.ModbusPollingTime,
Entity = modbusForm.ModbusEntity.ToString(),
MappedUAExpandedNodeID = NodeId.ToExpandedNodeId(_uaVariables[variableId].NodeId, Server.NamespaceUris).ToString(),
MappedUAFieldPath = fieldPath
};
_tags[assetId].Add(tag);
}
if (td.Base.ToLower().StartsWith("opc.tcp://"))
{
// create an asset tag and add to our list
GenericForm opcuaForm = JsonConvert.DeserializeObject<GenericForm>(form.ToString());
AssetTag tag = new()
{
Name = variableId,
Address = opcuaForm.Href,
UnitID = unitId,
Type = opcuaForm.Type.ToString(),
PollingInterval = (int)opcuaForm.PollingTime,
Entity = null,
MappedUAExpandedNodeID = NodeId.ToExpandedNodeId(_uaVariables[variableId].NodeId, Server.NamespaceUris).ToString(),
MappedUAFieldPath = fieldPath
};
_tags[assetId].Add(tag);
}
if (td.Base.ToLower().StartsWith("s7://"))
{
// create an asset tag and add to our list
S7Form s7Form = JsonConvert.DeserializeObject<S7Form>(form.ToString());
AssetTag tag = new()
{
Name = variableId,
Address = s7Form.Href,
UnitID = unitId,
Type = s7Form.Type.ToString(),
PollingInterval = (int)s7Form.PollingTime,
Entity = null,
MappedUAExpandedNodeID = NodeId.ToExpandedNodeId(_uaVariables[variableId].NodeId, Server.NamespaceUris).ToString(),
MappedUAFieldPath = fieldPath
};
_tags[assetId].Add(tag);
}
if (td.Base.ToLower().StartsWith("mcp://"))
{
// create an asset tag and add to our list
GenericForm mitsubishiForm = JsonConvert.DeserializeObject<GenericForm>(form.ToString());
AssetTag tag = new()
{
Name = variableId,
Address = mitsubishiForm.Href,
UnitID = unitId,
Type = mitsubishiForm.Type.ToString(),
PollingInterval = 1000,
Entity = null,
MappedUAExpandedNodeID = NodeId.ToExpandedNodeId(_uaVariables[variableId].NodeId, Server.NamespaceUris).ToString(),
MappedUAFieldPath = fieldPath
};
_tags[assetId].Add(tag);
}
if (td.Base.ToLower().StartsWith("eip://"))
{
// create an asset tag and add to our list
EIPForm eipForm = JsonConvert.DeserializeObject<EIPForm>(form.ToString());
AssetTag tag = new()
{
Name = variableId,
Address = eipForm.Href,
UnitID = unitId,
Type = eipForm.Type.ToString(),
PollingInterval = (int)eipForm.PollingTime,
Entity = null,
MappedUAExpandedNodeID = NodeId.ToExpandedNodeId(_uaVariables[variableId].NodeId, Server.NamespaceUris).ToString(),
MappedUAFieldPath = fieldPath
};
_tags[assetId].Add(tag);
}
if (td.Base.ToLower().StartsWith("ads://"))
{
// create an asset tag and add to our list
GenericForm adsForm = JsonConvert.DeserializeObject<GenericForm>(form.ToString());
AssetTag tag = new()
{
Name = variableId,
Address = adsForm.Href,
UnitID = unitId,
Type = adsForm.Type.ToString(),
PollingInterval = (int)adsForm.PollingTime,
Entity = null,
MappedUAExpandedNodeID = NodeId.ToExpandedNodeId(_uaVariables[variableId].NodeId, Server.NamespaceUris).ToString(),
MappedUAFieldPath = fieldPath
};
_tags[assetId].Add(tag);
}
if (td.Base.ToLower().StartsWith("bacnet://"))
{
// create an asset tag and add to our list
GenericForm bacnetForm = JsonConvert.DeserializeObject<GenericForm>(form.ToString());
AssetTag tag = new()
{
Name = variableId,
Address = bacnetForm.Href,
UnitID = unitId,
Type = bacnetForm.Type.ToString(),
PollingInterval = 1000,
Entity = null,
MappedUAExpandedNodeID = NodeId.ToExpandedNodeId(_uaVariables[variableId].NodeId, Server.NamespaceUris).ToString(),
MappedUAFieldPath = fieldPath
};
_tags[assetId].Add(tag);
}
}
private void AssetConnectionTest(ThingDescription td, out byte unitId)
{
unitId = 1;
IAsset assetInterface = null;
if (td.Base.ToLower().StartsWith("modbus+tcp://"))
{
string[] address = td.Base.Split(new char[] { ':', '/' });
if ((address.Length != 6) || (address[0] != "modbus+tcp"))
{
throw new Exception("Expected Modbus server address in the format modbus+tcp://ipaddress:port/unitID!");
}
// check if we can reach the Modbus asset
unitId = byte.Parse(address[5]);
ModbusTCPClient client = new();
client.Connect(address[3], int.Parse(address[4]));
assetInterface = client;
}
if (td.Base.ToLower().StartsWith("opc.tcp://"))
{
string[] address = td.Base.Split(new char[] { ':', '/' });
if ((address.Length != 5) || (address[0] != "opc.tcp"))
{
throw new Exception("Expected OPC UA server address in the format opc.tcp://ipaddress:port!");
}
// check if we can reach the OPC UA asset
UAClient client = new();
client.Connect(address[3], int.Parse(address[4]));
assetInterface = client;
}
if (td.Base.ToLower().StartsWith("s7://"))
{
string[] address = td.Base.Split(new char[] { ':', '/' });
if ((address.Length != 5) || (address[0] != "s7"))
{
throw new Exception("Expected S7 PLC address in the format s7://ipaddress:port!");
}
// check if we can reach the Siemens asset
SiemensClient client = new();
client.Connect(address[3], int.Parse(address[4]));
assetInterface = client;
}
if (td.Base.ToLower().StartsWith("mcp://"))
{
string[] address = td.Base.Split(new char[] { ':', '/' });
if ((address.Length != 5) || (address[0] != "mcp"))
{
throw new Exception("Expected Mitsubishi PLC address in the format mcp://ipaddress:port!");
}
// check if we can reach the Mitsubishi asset
MitsubishiClient client = new();
client.Connect(address[3], int.Parse(address[4]));
assetInterface = client;
}
if (td.Base.ToLower().StartsWith("eip://"))
{
string[] address = td.Base.Split(new char[] { ':', '/' });
if ((address.Length != 4) || (address[0] != "eip"))
{
throw new Exception("Expected Rockwell PLC address in the format eip://ipaddress:port!");
}
// check if we can reach the Ethernet/IP asset
RockwellClient client = new();
client.Connect(address[3], 0);
assetInterface = client;
}
if (td.Base.ToLower().StartsWith("ads://"))
{
string[] address = td.Base.Split(new char[] { ':', '/' });
if ((address.Length != 6) || (address[0] != "ads"))
{
throw new Exception("Expected Beckhoff PLC address in the format ads://ipaddress:port!");
}
// check if we can reach the Beckhoff asset
BeckhoffClient client = new();
client.Connect(address[3] + ":" + address[4], int.Parse(address[5]));
assetInterface = client;
}
if (td.Base.ToLower().StartsWith("bacnet://"))
{
string[] address = td.Base.Split(new char[] { ':', '/' });
if ((address.Length != 5) || (address[0] != "bacnet"))
{
throw new Exception("Expected BACNet device address in the format bacnet://ipaddress/deviceId!");
}
// check if we can reach the BACNet asset
BACNetClient client = new();
client.Connect(address[3] + "/" + address[4], 0);
assetInterface = client;
}
_assets.Add(td.Name, assetInterface);
}
private ExpandedNodeId ParseExpandedNodeId(string nodeString)
{
if (!string.IsNullOrEmpty(nodeString))
{
string[] parentNodeDetails = nodeString.Split('=', ';');
if (parentNodeDetails.Length > 3 && parentNodeDetails[0] == "nsu" && parentNodeDetails[2] == "i")
{
string namespaceUri = parentNodeDetails[1];
if (!NamespaceUris.Contains(namespaceUri))
{
return null;
}
switch (parentNodeDetails[2])
{
case "i":
return new ExpandedNodeId(uint.Parse(parentNodeDetails[3]),
(ushort)Server.NamespaceUris.GetIndex(namespaceUri));
case "s":
return new ExpandedNodeId(parentNodeDetails[3],
(ushort)Server.NamespaceUris.GetIndex(namespaceUri));
default:
return null;
}
}
}
return null;
}
private BaseDataVariableState CreateVariable(NodeState parent, string name, ExpandedNodeId type, ushort namespaceIndex, bool writeable = false, object value = null)
{
BaseDataVariableState variable = new BaseDataVariableState(parent)
{
SymbolicName = name,
ReferenceTypeId = ReferenceTypes.Organizes,
NodeId = new NodeId(name, namespaceIndex),
BrowseName = new QualifiedName(name, namespaceIndex),
DisplayName = new Ua.LocalizedText("en", name),
WriteMask = AttributeWriteMask.None,
UserWriteMask = AttributeWriteMask.None,
AccessLevel = AccessLevels.CurrentRead,
DataType = ExpandedNodeId.ToNodeId(type, Server.NamespaceUris),
Value = value,
OnReadValue = OnReadValue
};
if (writeable)
{
variable.AccessLevel = AccessLevels.CurrentReadOrWrite;
variable.UserAccessLevel = AccessLevels.CurrentReadOrWrite;
variable.UserWriteMask = AttributeWriteMask.ValueForVariableType;
variable.WriteMask = AttributeWriteMask.ValueForVariableType;
variable.OnWriteValue = OnWriteValue;
}
parent?.AddChild(variable);
parent?.AddReference(ExpandedNodeId.ToNodeId(UAModel.WoT_Con.ReferenceTypeIds.HasWoTComponent, Server.NamespaceUris), false, variable.NodeId);
AddPredefinedNode(SystemContext, variable);
return variable;
}
private ServiceResult OnReadValue(ISystemContext context, NodeState node, NumericRange indexRange, QualifiedName dataEncoding, ref object value, ref StatusCode statusCode, ref DateTime timestamp)
{
bool provisioningMode = (Directory.EnumerateFiles(Path.Combine(Directory.GetCurrentDirectory(), "pki", "issuer", "certs")).Count() == 0);
if (provisioningMode)
{
return new ServiceResult(StatusCodes.BadNotReadable, "Access to UA Edge Translator is limited while in provisioning mode!");
}
BaseDataVariableState variable = node as BaseDataVariableState;
if (node.DisplayName.Text == "SupportedWoTBindings")
{
value = _uaVariables[node.DisplayName.Text].Value;
timestamp = _uaVariables[node.DisplayName.Text].Timestamp;
statusCode = StatusCodes.Good;
return ServiceResult.Good;
}
foreach (KeyValuePair<string, List<AssetTag>> tags in _tags)
{
string assetId = tags.Key;
foreach (AssetTag tag in tags.Value)
{
try
{
if (tag.MappedUAExpandedNodeID.ToString() == NodeId.ToExpandedNodeId(variable.NodeId, context.NamespaceUris).ToString())
{
value = _uaVariables[tag.Name].Value;
timestamp = _uaVariables[tag.Name].Timestamp;
statusCode = StatusCodes.Good;
return ServiceResult.Good;
}
}
catch (Exception ex)
{
Log.Logger.Error(ex.Message, ex);
return new ServiceResult(ex);
}
}