forked from OPCF-Members/Opc2Aml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNodeSetToAML.cs
3542 lines (2980 loc) · 160 KB
/
NodeSetToAML.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
/* ========================================================================
* Copyright (c) 2005-2021 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Collections.Generic;
using Opc.Ua;
using Aml.Engine.AmlObjects;
using Aml.Engine.CAEX;
using Aml.Engine.CAEX.Extensions;
using UADataType = MarkdownProcessor.NodeSet.UADataType;
using UAInstance = MarkdownProcessor.NodeSet.UAInstance;
using UANode = MarkdownProcessor.NodeSet.UANode;
using UAObject = MarkdownProcessor.NodeSet.UAObject;
using UAType = MarkdownProcessor.NodeSet.UAType;
using UAVariable = MarkdownProcessor.NodeSet.UAVariable;
using DataTypeField = MarkdownProcessor.NodeSet.DataTypeField;
using Aml.Engine.Adapter;
using System.Xml.Linq;
using System.Linq;
using System.Diagnostics;
using System.Net;
using NodeSetToAmlUtils;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Xml;
using System.IO;
using Opc2Aml;
namespace MarkdownProcessor
{
public class NodeSetToAML
{
private const string ATLPrefix = "ATL_";
private const string ICLPrefix = "ICL_";
private const string RCLPrefix = "RCL_";
private const string SUCPrefix = "SUC_";
private const string ListOf = "ListOf";
private const string MetaModelName = "OpcAmlMetaModel";
private const string UaBaseRole = "UaBaseRole";
private const string MethodNodeClass = "UaMethodNodeClass";
private const string RefClassConnectsToPath = "RefClassConnectsToPath";
private const string IsSource = "IsSource";
private const string ForwardPrefix = "f";
private const string ReversePrefix = "r";
private const string Enumeration = "Enumeration";
private ModelManager m_modelManager;
private CAEXDocument m_cAEXDocument;
private AttributeTypeLibType m_atl_temp;
private readonly NodeId PropertyTypeNodeId = new NodeId(68, 0);
private readonly NodeId HasSubTypeNodeId = new NodeId(45, 0);
private readonly NodeId HasPropertyNodeId = new NodeId(46, 0);
private readonly NodeId QualifiedNameNodeId = new NodeId(20, 0);
private readonly NodeId NodeIdNodeId = new NodeId(17, 0);
private readonly NodeId ExpandedNodeIdNodeId = new NodeId(18, 0);
private readonly NodeId RelativePathElementNodeId = new NodeId(537, 0);
private readonly NodeId RelativePathNodeId = new NodeId(540, 0);
private readonly NodeId GuidNodeId = new NodeId(14, 0);
private readonly NodeId BaseDataTypeNodeId = new NodeId(24, 0);
private readonly NodeId NumberNodeId = new NodeId(26, 0);
private readonly NodeId OptionSetStructureNodeId = new NodeId(12755, 0);
private readonly NodeId AggregatesNodeId = new NodeId(44, 0);
private readonly NodeId HasInterfaceNodeId = new NodeId(17603, 0);
private readonly NodeId HasTypeDefinitionNodeId = new NodeId(40, 0);
private readonly NodeId HasModellingRuleNodeId = new NodeId(37, 0);
private readonly NodeId BaseInterfaceNodeId = new NodeId(17602, 0);
private readonly NodeId RootNodeId = new NodeId(84, 0);
private readonly NodeId HierarchicalNodeId = new NodeId(33, 0);
private readonly NodeId OrganizesNodeId = new NodeId(35, 0);
private readonly NodeId TypesFolderNodeId = new NodeId(86, 0);
private readonly NodeId TwoStateDiscreteNodeId = new NodeId(2373, 0);
private readonly NodeId MultiStateDiscreteNodeId = new NodeId(2376, 0);
private readonly NodeId MultiStateValueDiscreteNodeId = new NodeId(11238, 0);
private readonly NodeId EnumerationNodeId = Opc.Ua.DataTypeIds.Enumeration;
private readonly NodeId IntegerNodeId = Opc.Ua.DataTypeIds.Integer;
private readonly System.Xml.Linq.XNamespace defaultNS = "http://www.dke.de/CAEX";
private const string uaNamespaceURI = "http://opcfoundation.org/UA/";
private const string OpcLibInfoNamespace = "http://opcfoundation.org/UA/FX/2021/08/OpcUaLibInfo.xsd";
private UANode structureNode;
private readonly List<string> ExcludedDataTypeList = new List<string>() { "InstanceNode", "TypeNode" };
private Dictionary<string, Dictionary<string,string>> LookupNames = new Dictionary<string, Dictionary<string, string>>();
private HashSet<string> ExtensionObjectExclusions = null;
private Dictionary<string, Dictionary<string, DataTypeField>> ReferenceAttributeMap =
new Dictionary<string, Dictionary<string, DataTypeField>>();
private readonly string[] NodeId_IdAttributeNames = { "NumericId", "StringId", "GuidId", "OpaqueId" };
private List<string> PreventInfiniteRecursionList = new List<string>();
private const int ua2xslookup_count = 18;
private const int ua2xslookup_uaname = 0;
private const int ua2xslookup_xsname = 1;
private readonly string[,] ua2xsLookup = new string[ua2xslookup_count, 2] {
{ "Boolean" , "xs:boolean" },
{ "SByte" , "xs:Byte" },
{ "Byte" , "xs:unsignedByte" },
{ "Int16" , "xs:short" },
{ "UInt16" , "xs:unsignedShort" },
{ "Int32" , "xs:int" },
{ "UInt32" , "xs:unsignedInt" },
{ "Int64" , "xs:long" },
{ "UInt64" , "xs:unsignedLong" },
{ "Float" , "xs:float" },
{ "Double" , "xs:double" },
{ "String" , "xs:string" },
{ "DateTime" , "xs:dateTime" },
{ "ByteString" , "xs:base64Binary" },
{ "LocalizedText" , "xs:string" },
{ "QualifiedName" , "xs:anyURI" },
{ "StatusCode" , "xs:unsignedInt" },
{ Enumeration , "xs:int" }
};
public NodeSetToAML(ModelManager modelManager)
{
m_modelManager = modelManager;
}
public T FindNode<T>(NodeId sourceId) where T : UANode
{
UANode node = null;
node = m_modelManager.FindNode<T>(sourceId);
// display error message and throw
if( node == null )
throw new Exception( "Can't find node: " + sourceId.ToString() + " Is your nodeset file missing a <RequiredModel> element?");
return node as T;
}
public void CreateAML(string modelPath, string modelName = null)
{
string modelUri = m_modelManager.LoadModel(modelPath, null, null);
structureNode = m_modelManager.FindNodeByName("Structure");
if (modelName == null)
modelName = modelPath;
Utils.LogInfo( "CreateAML for model {0}", modelName );
m_cAEXDocument = CAEXDocument.New_CAEXDocument();
var cAEXDocumentTemp = CAEXDocument.New_CAEXDocument();
// adds the base libraries to the document
AutomationMLInterfaceClassLibType.InterfaceClassLib(m_cAEXDocument);
AutomationMLBaseRoleClassLibType.RoleClassLib(m_cAEXDocument);
AutomationMLBaseAttributeTypeLibType.AttributeTypeLib(m_cAEXDocument);
AutomationMLBaseAttributeTypeLibType.AttributeTypeLib(cAEXDocumentTemp);
AutomationMLInterfaceClassLibType.InterfaceClassLib(cAEXDocumentTemp);
// process each model in order (with the base UA Model first )
AddMetaModelLibraries(m_cAEXDocument);
List<ModelInfo> MyModelInfoList = new List<ModelInfo>();
// Get the models in the correct order for processing the base models first
foreach (var modelInfo in m_modelManager.ModelNamespaceIndexes)
{
if (modelInfo != m_modelManager.DefaultModel)
MyModelInfoList.Add(modelInfo);
}
MyModelInfoList.Add(m_modelManager.DefaultModel);
OrderModelInfo orderModelInfo = new OrderModelInfo();
List<ModelInfo> orderedModelList = orderModelInfo.GetProcessOrder(MyModelInfoList);
foreach( var modelInfo in orderedModelList )
{
Utils.LogInfo( "{0} processing model {1} NamespaceIndex {2}",
modelName, modelInfo.NamespaceUri, modelInfo.NamespaceIndex );
AttributeTypeLibType atl = null;
InterfaceClassLibType icl = null;
RoleClassLibType rcl = null;
SystemUnitClassLibType scl = null;
m_atl_temp = cAEXDocumentTemp.CAEXFile.AttributeTypeLib.Append(ATLPrefix + modelInfo.NamespaceUri);
AddLibraryHeaderInfo(m_atl_temp as CAEXBasicObject, modelInfo);
// create the InterfaceClassLibrary
var icl_temp = cAEXDocumentTemp.CAEXFile.InterfaceClassLib.Append(ICLPrefix + modelInfo.NamespaceUri);
AddLibraryHeaderInfo(icl_temp as CAEXBasicObject, modelInfo);
// Create the RoleClassLibrary
var rcl_temp = cAEXDocumentTemp.CAEXFile.RoleClassLib.Append(RCLPrefix + modelInfo.NamespaceUri);
// var rcl_temp = m_cAEXDocument.CAEXFile.RoleClassLib.Append(RCLPrefix + modelInfo.NamespaceUri);
AddLibraryHeaderInfo(rcl_temp as CAEXBasicObject, modelInfo);
// Create the SystemUnitClassLibrary
var scl_temp = cAEXDocumentTemp.CAEXFile.SystemUnitClassLib.Append(SUCPrefix + modelInfo.NamespaceUri);
// var scl_temp = m_cAEXDocument.CAEXFile.SystemUnitClassLib.Append(SUCPrefix + modelInfo.NamespaceUri);
AddLibraryHeaderInfo(scl_temp as CAEXBasicObject, modelInfo);
SortedDictionary<string, AttributeFamilyType> SortedDataTypes = new SortedDictionary<string, AttributeFamilyType>();
SortedDictionary<string, NodeId> SortedReferenceTypes = new SortedDictionary<string, NodeId>();
SortedDictionary<string, NodeId> SortedObjectTypes = new SortedDictionary<string, NodeId>(); // also contains VariableTypes
Dictionary<string, UANode> fieldDefinitions = new Dictionary<string, UANode>();
foreach (KeyValuePair<string, UANode> node in modelInfo.Types)
{
switch (node.Value.NodeClass)
{
case NodeClass.DataType:
AttributeFamilyType toAdd = ProcessDataType( node.Value );
if( toAdd != null )
{
if( !SortedDataTypes.ContainsKey( node.Value.DecodedBrowseName.Name ) )
{
SortedDataTypes.Add( node.Value.DecodedBrowseName.Name, toAdd );
fieldDefinitions.Add( node.Value.DecodedBrowseName.Name, node.Value );
}
}
break;
case NodeClass.ReferenceType:
SortedReferenceTypes.Add(node.Value.DecodedBrowseName.Name, node.Value.DecodedNodeId);
break;
case NodeClass.ObjectType:
case NodeClass.VariableType:
if (!SortedObjectTypes.ContainsKey(node.Value.DecodedBrowseName.Name))
SortedObjectTypes.Add(node.Value.DecodedBrowseName.Name, node.Value.DecodedNodeId);
break;
}
}
foreach( KeyValuePair<string, AttributeFamilyType> dicEntry in SortedDataTypes)
{
if (atl == null)
{
atl = m_cAEXDocument.CAEXFile.AttributeTypeLib.Append(ATLPrefix + modelInfo.NamespaceUri);
AddLibraryHeaderInfo(atl as CAEXBasicObject, modelInfo);
}
atl.AttributeType.Insert( dicEntry.Value, false); // insert into the AML document in alpha order
}
foreach( var dicEntry in SortedDataTypes) // cteate the ListOf versions
{
atl.AttributeType.Insert(CreateListOf(dicEntry.Value), false); // insert into the AML document in alpha order
}
if( atl != null )
{
foreach( AttributeFamilyType attribute in atl.AttributeType )
{
if( fieldDefinitions.ContainsKey( attribute.Name ) )
{
AddAttributeData( attribute, fieldDefinitions[ attribute.Name ] );
}
}
}
foreach( var refType in SortedReferenceTypes)
{
ProcessReferenceType(ref icl_temp, refType.Value);
}
// reorder icl_temp an put in the real icl in alpha order
foreach( var refType in SortedReferenceTypes)
{
string iclpath = BuildLibraryReference(ICLPrefix, modelInfo.NamespaceUri, refType.Key);
InterfaceClassType ict = icl_temp.CAEXDocument.FindByPath(iclpath) as InterfaceClassType;
if (ict != null)
{
if (icl == null)
{
// Create the InterfaceClassLibrary
icl = m_cAEXDocument.CAEXFile.InterfaceClassLib.Append(ICLPrefix + modelInfo.NamespaceUri);
AddLibraryHeaderInfo(icl as CAEXBasicObject, modelInfo);
}
icl.Insert(ict, false);
}
}
Utils.LogInfo( "Processing SystemUnitClass Types" );
foreach( var obType in SortedObjectTypes)
{
FindOrAddSUC(ref scl_temp, ref rcl_temp, obType.Value);
}
// re-order the rcl_temp and scl_temp in alpha order into the real rcl and scl
foreach( var obType in SortedObjectTypes)
{
string sucpath = BuildLibraryReference(SUCPrefix, modelInfo.NamespaceUri, obType.Key);
SystemUnitFamilyType sft = scl_temp.CAEXDocument.FindByPath(sucpath) as SystemUnitFamilyType;
if (sft != null)
{
if (scl == null)
{
scl = m_cAEXDocument.CAEXFile.SystemUnitClassLib.Append(SUCPrefix + modelInfo.NamespaceUri);
AddLibraryHeaderInfo(scl as CAEXBasicObject, modelInfo);
}
scl.Insert(sft, false);
}
string rclpath = BuildLibraryReference(RCLPrefix, modelInfo.NamespaceUri, obType.Key);
var rft = rcl_temp.CAEXDocument.FindByPath(rclpath) as RoleFamilyType;
if (rft != null)
{
if (rcl == null)
{
rcl = m_cAEXDocument.CAEXFile.RoleClassLib.Append(RCLPrefix + modelInfo.NamespaceUri);
AddLibraryHeaderInfo(rcl as CAEXBasicObject, modelInfo);
}
rcl.Insert(rft, false);
}
}
}
Utils.LogInfo( "Creating Instances" );
CreateInstances(); // add the instances for each model
Utils.LogInfo( "Creating Instances Complete" );
RemoveTypeOnly();
Utils.LogInfo( "Remove Type Only information Complete" );
// write out the AML file
// var OutFilename = modelName + ".aml";
// m_cAEXDocument.SaveToFile(OutFilename, true);
FileInfo internalFileInfo = new FileInfo( modelName );
FileInfo outputFileInfo = new FileInfo( modelName + ".amlx" );
var container = new AutomationMLContainer(outputFileInfo.FullName, System.IO.FileMode.Create);
container.AddRoot(m_cAEXDocument.SaveToStream(true), new Uri("/" + internalFileInfo.Name + ".aml", UriKind.Relative));
container.Close();
Utils.LogInfo( "Amlx Container Created for model " + modelName );
}
private void AddLibraryHeaderInfo(CAEXBasicObject bo, ModelInfo modelInfo = null)
{
bo.Description = "AutomationML Library to support OPC UA meta model";
bo.Copyright = "\xA9 OPC Foundation";
if (modelInfo != null)
{
XNamespace ns = OpcLibInfoNamespace;
bo.Description = "AutomationML Library auto-generated from OPC UA Nodeset file for OPC UA Namepace: " + modelInfo.NamespaceUri;
var ab = new XElement(ns + "OpcUaLibInfo");
var ai = new XElement(ns + "OpcUaNamespaceUri", modelInfo.NamespaceUri);
ab.Add(ai);
ai = new XElement(ns + "ModelVersion", modelInfo.NodeSet.Models[0].Version);
ab.Add(ai);
ai = new XElement(ns + "ModelPublicationDate", modelInfo.PublicationDate);
ab.Add(ai);
bo.AdditionalInformation.Append(ab);
}
var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
var aj = new XElement(defaultNS + "Nodeset2AmlToolVersion");
aj.SetValue(version);
bo.AdditionalInformation.Append(aj);
var buildDate = new DateTime(2000, 1, 1).AddDays(version.Build).AddSeconds(version.Revision * 2);
aj = new XElement(defaultNS + "Nodeset2AmlToolBuildDate");
aj.SetValue(buildDate.ToUniversalTime());
bo.AdditionalInformation.Append(aj);
}
private AttributeValueRequirementType BuiltInTypeConstraint()
{
AttributeValueRequirementType avrt = new AttributeValueRequirementType(new System.Xml.Linq.XElement(defaultNS + "Constraint"));
avrt.Name = "BuiltInType Constraint";
var res = avrt.New_NominalType();
foreach (string name in Enum.GetNames(typeof(BuiltInType)))
{
res.RequiredValue.Append(name);
}
return avrt;
}
private AttributeValueRequirementType AttributeIdConstraint()
{
AttributeValueRequirementType avrt = new AttributeValueRequirementType(new System.Xml.Linq.XElement(defaultNS + "Constraint"));
avrt.Name = "AttributeId Constraint";
var res = avrt.New_NominalType();
foreach (string name in Attributes.GetBrowseNames())
{
res.RequiredValue.Append(name);
}
return avrt;
}
private void AddMetaModelLibraries(CAEXDocument doc)
{
// add ModelingRuleType (that does not exist in UA) to ATL
AttributeTypeLibType atl_meta = doc.CAEXFile.AttributeTypeLib.Append(ATLPrefix + MetaModelName);
AddLibraryHeaderInfo(atl_meta as CAEXBasicObject);
var added = new AttributeFamilyType(new System.Xml.Linq.XElement(defaultNS + "AttributeType"));
AttributeType added2 = null;
var att = added as AttributeTypeType;
added.Name = "ModellingRuleType";
att.AttributeDataType = "xs:string";
AttributeValueRequirementType avrt = new AttributeValueRequirementType(new System.Xml.Linq.XElement(defaultNS + "Constraint"));
avrt.Name = added.Name + " Constraint";
var res = avrt.New_NominalType();
res.RequiredValue.Append("ExposesItsArray");
res.RequiredValue.Append("Mandatory");
res.RequiredValue.Append("MandatoryPlaceholder");
res.RequiredValue.Append("Optional");
res.RequiredValue.Append("OptionalPlaceholder");
att.Constraint.Insert(avrt);
atl_meta.AttributeType.Insert(added, false);
// add BuiltInType enumeration (that does not exist in UA) to ATL
added = new AttributeFamilyType(new System.Xml.Linq.XElement(defaultNS + "AttributeType"));
att = added as AttributeTypeType;
added.Name = "BuiltInType";
att.AttributeDataType = "xs:string";
att.Constraint.Insert(BuiltInTypeConstraint());
atl_meta.AttributeType.Insert(added, false);
// add AttributeId enumeration (that does not exist in UA) to ATL
added = new AttributeFamilyType(new System.Xml.Linq.XElement(defaultNS + "AttributeType"));
att = added as AttributeTypeType;
added.Name = "AttributeId";
att.AttributeDataType = "xs:string";
att.Constraint.Insert(AttributeIdConstraint());
atl_meta.AttributeType.Insert(added, false);
// add NamespaceUri
var NamespaceUriAttr = new AttributeFamilyType(new System.Xml.Linq.XElement(defaultNS + "AttributeType"));
att = NamespaceUriAttr as AttributeTypeType;
NamespaceUriAttr.Name = "NamespaceUri";
att.AttributeDataType = "xs:anyURI";
atl_meta.AttributeType.Insert(NamespaceUriAttr, false);
// add ExplicitNodeId
var ExplicitNodeIdAttr = new AttributeFamilyType(new System.Xml.Linq.XElement(defaultNS + "AttributeType"));
att = ExplicitNodeIdAttr as AttributeTypeType;
ExplicitNodeIdAttr.Name = "ExplicitNodeId";
added2 = new AttributeType(new System.Xml.Linq.XElement(defaultNS + "Attribute"));
added2.Name = "NamespaceUri";
added2.RecreateAttributeInstance(NamespaceUriAttr);
ExplicitNodeIdAttr.Insert(added2, false);
added2 = new AttributeType(new System.Xml.Linq.XElement(defaultNS + "Attribute"));
added2.Name= "NumericId";
added2.AttributeDataType = "xs:long";
ExplicitNodeIdAttr.Insert(added2, false);
added2 = new AttributeType(new System.Xml.Linq.XElement(defaultNS + "Attribute"));
added2.Name = "StringId";
added2.AttributeDataType = "xs:string";
ExplicitNodeIdAttr.Insert(added2, false);
added2 = new AttributeType(new System.Xml.Linq.XElement(defaultNS + "Attribute"));
added2.Name = "GuidId";
added2.AttributeDataType = "xs:string";
ExplicitNodeIdAttr.Insert(added2, false);
added2 = new AttributeType(new System.Xml.Linq.XElement(defaultNS + "Attribute"));
added2.Name = "OpaqueId";
added2.AttributeDataType = "xs:base64Binary";
ExplicitNodeIdAttr.Insert(added2, false);
atl_meta.AttributeType.Insert(ExplicitNodeIdAttr, false);
// add Alias
var AliasAttr = new AttributeFamilyType(new System.Xml.Linq.XElement(defaultNS + "AttributeType"));
att = AliasAttr as AttributeTypeType;
AliasAttr.Name = "Alias";
added2 = new AttributeType(new System.Xml.Linq.XElement(defaultNS + "Attribute"));
added2.Name = "AliasName";
added2.AttributeDataType = "xs:string";
AliasAttr.Insert(added2, false);
added2 = new AttributeType(new System.Xml.Linq.XElement(defaultNS + "Attribute"));
added2.Name = "ReferenceTypeFilter";
added2.RecreateAttributeInstance(ExplicitNodeIdAttr);
AliasAttr.Insert(added2, false);
atl_meta.AttributeType.Insert(AliasAttr, false);
// add UABaseRole to the RCL
var rcl_meta = m_cAEXDocument.CAEXFile.RoleClassLib.Append(RCLPrefix + MetaModelName);
var br = rcl_meta.New_RoleClass(UaBaseRole);
br.RefBaseClassPath = "AutomationMLBaseRoleClassLib/AutomationMLBaseRole";
AddLibraryHeaderInfo(rcl_meta as CAEXBasicObject);
// add meta model SUC
var suc_meta = m_cAEXDocument.CAEXFile.SystemUnitClassLib.Append(SUCPrefix + MetaModelName);
// add MethodNodeClass to the SUC
// This will add a guid ID, as UaMethodNodeClass is not in the Nodeset file
var methodNodeClass = suc_meta.New_SystemUnitClass( MethodNodeClass );
// Give this a known repeatable ID, as there is no node ID for it.
string methodNodeClassUniqueId = "686619c7-0101-4869-b398-aa0f98bc5f54";
methodNodeClass.ID = methodNodeClassUniqueId;
methodNodeClass.New_SupportedRoleClass( RCLPrefix + MetaModelName + "/" + UaBaseRole, false );
// Issue 16 Add BrowseName to SUC UaMethodNodeClass
// Manually add these to simulate what the AddModifyAttribute would do if it were possible
AttributeType browseNameAttributeType = methodNodeClass.Attribute.Append( "BrowseName" );
browseNameAttributeType.RefAttributeType = "[" + ATLPrefix + Opc.Ua.Namespaces.OpcUa + "]/[QualifiedName]";
AttributeType namespaceUriAttributeType = browseNameAttributeType.Attribute.Append( "NamespaceURI" );
namespaceUriAttributeType.AttributeDataType = "xs:anyURI";
AttributeType nameAttributeType = browseNameAttributeType.Attribute.Append( "Name" );
nameAttributeType.AttributeDataType = "xs:string";
AddLibraryHeaderInfo( suc_meta as CAEXBasicObject);
}
private void AddBaseNodeClassAttributes( AttributeSequence seq, UANode uanode, UANode basenode = null)
{
// only set the value if different from the base node
string baseuri = "";
if (basenode != null )
baseuri = m_modelManager.ModelNamespaceIndexes[basenode.DecodedNodeId.NamespaceIndex].NamespaceUri;
string myuri = m_modelManager.ModelNamespaceIndexes[uanode.DecodedNodeId.NamespaceIndex].NamespaceUri;
var nodeId = seq["NodeId"];
if (uanode.DecodedNodeId.IsNullNodeId == false)
{
ExpandedNodeId expandedNodeId = new ExpandedNodeId(uanode.DecodedNodeId, myuri);
Variant variant = new Variant(expandedNodeId);
nodeId = AddModifyAttribute(seq, "NodeId", "NodeId", variant);
}
var browse = seq["BrowseName"];
if (browse == null)
{
browse = AddModifyAttribute(seq, "BrowseName", "QualifiedName", Variant.Null);
}
if (myuri != baseuri)
{
var uriatt = browse.Attribute["NamespaceURI"];
uriatt.Value = myuri;
}
if (uanode.DisplayName != null &&
uanode.DisplayName.Length > 0 &&
uanode.DisplayName[0].Value != uanode.DecodedBrowseName.Name)
{
AddModifyAttribute(seq, "DisplayName", "LocalizedText",
uanode.DisplayName[0].Value);
}
if (uanode.Description != null &&
uanode.Description.Length > 0 &&
uanode.Description[0].Value.Length > 0)
{
AddModifyAttribute(seq, "Description", "LocalizedText",
uanode.Description[0].Value);
}
UAType uaType = uanode as UAType;
if ( uaType != null && uaType.IsAbstract )
{
AddModifyAttribute(seq, "IsAbstract", "Boolean", uaType.IsAbstract);
}
}
private AttributeType AddModifyAttribute(AttributeSequence seq, string name, string refDataType, Variant val, bool bListOf = false, string sURI = uaNamespaceURI)
{
string sUADataType = refDataType;
var DataTypeNode = m_modelManager.FindNode<UANode>(refDataType);
if (DataTypeNode != null)
{
sUADataType = DataTypeNode.DecodedBrowseName.Name;
sURI = m_modelManager.FindModelUri(DataTypeNode.DecodedNodeId);
}
string ListOfPrefix = "";
if (bListOf == true)
ListOfPrefix = ListOf;
string path = BuildLibraryReference(ATLPrefix, sURI, ListOfPrefix + sUADataType);
var ob = m_cAEXDocument.FindByPath(path);
var at = ob as AttributeFamilyType;
AttributeType a = seq[name]; //find the existing attribute with the name
if (a == null)
{
if (bListOf == false && val.TypeInfo != null) // look for reasons not to add the attribute because missing == default value
{
if (name == "ValueRank" && val == -2 )
return null;
if (name == "IsSource" && val == false)
return null;
if (name == "Symmetric" && val == false)
return null;
}
a = seq.Append(name); // not found so create a new one
}
a.RecreateAttributeInstance(at);
if (val.TypeInfo != null)
{
if (bListOf == true)
{
string nodeName = "";
string referenceName = "";
CAEXWrapper reference = seq.CAEXOwner;
if (reference != null)
{
referenceName = reference.Name();
CAEXWrapper referenceParent = reference.CAEXParent;
if (referenceParent != null)
{
nodeName = referenceParent.Name();
}
}
bool addElements = true;
switch( val.TypeInfo.BuiltInType )
{
case BuiltInType.LocalizedText:
{
if( refDataType == "LocalizedText" && referenceName == "EnumStrings" )
{
addElements = false;
AttributeTypeType attributeType = a as AttributeTypeType;
if( attributeType != null )
{
AttributeValueRequirementType stringValueRequirement = new AttributeValueRequirementType(
new System.Xml.Linq.XElement( defaultNS + "Constraint" ) );
stringValueRequirement.Name = nodeName + " Constraint";
attributeType.AttributeDataType = "xs:string";
NominalScaledTypeType stringValueNominalType = stringValueRequirement.New_NominalType();
Opc.Ua.LocalizedText[] values = val.Value as Opc.Ua.LocalizedText[];
if( values != null )
{
foreach( Opc.Ua.LocalizedText value in values )
{
stringValueNominalType.RequiredValue.Append( value.Text );
}
attributeType.Constraint.Insert( stringValueRequirement );
}
}
}
break;
}
case BuiltInType.ExtensionObject:
{
if( refDataType == "EnumValueType" && referenceName == "EnumValues" )
{
addElements = false;
AttributeTypeType attributeType = a as AttributeTypeType;
if( attributeType != null )
{
AttributeValueRequirementType stringValueRequirement = new AttributeValueRequirementType(
new System.Xml.Linq.XElement( defaultNS + "Constraint" ) );
stringValueRequirement.Name = nodeName + " Constraint";
attributeType.AttributeDataType = "xs:string";
NominalScaledTypeType stringValueNominalType = stringValueRequirement.New_NominalType();
ExtensionObject[] values = val.Value as ExtensionObject[];
if( values != null )
{
foreach( ExtensionObject value in values )
{
EnumValueType enumValueType = value.Body as EnumValueType;
if( enumValueType != null )
{
stringValueNominalType.RequiredValue.Append( enumValueType.DisplayName.Text );
}
}
attributeType.Constraint.Insert( stringValueRequirement );
}
}
}
break;
}
}
if( addElements )
{
IList valueAsList = val.Value as IList;
if( valueAsList != null )
{
for( int index = 0; index < valueAsList.Count; index++ )
{
Variant elementVariant = new Variant( valueAsList[ index ] );
bool elementListOf = elementVariant.TypeInfo.ValueRank >= ValueRanks.OneDimension;
AddModifyAttribute( a.Attribute, index.ToString(), refDataType,
elementVariant, elementListOf, sURI );
}
}
}
}
else
{
bool handled = true;
switch (val.TypeInfo.BuiltInType) // TODO -- consider supporting setting values for more complicated types (enums, structures, Qualified Names ...) and arrays
{
case BuiltInType.Boolean:
case BuiltInType.SByte:
case BuiltInType.Byte:
case BuiltInType.Int16:
case BuiltInType.UInt16:
case BuiltInType.Int32:
case BuiltInType.UInt32:
case BuiltInType.Int64:
case BuiltInType.UInt64:
case BuiltInType.Float:
case BuiltInType.Double:
case BuiltInType.String:
case BuiltInType.DateTime:
case BuiltInType.Guid:
case BuiltInType.XmlElement:
case BuiltInType.Number:
case BuiltInType.Integer:
case BuiltInType.UInteger:
case BuiltInType.Enumeration:
{
a.DefaultAttributeValue = a.AttributeValue = val;
break;
}
case BuiltInType.ByteString:
{
byte[] bytes = val.Value as byte[];
if ( bytes != null )
{
string encoded = Convert.ToBase64String( bytes, 0, bytes.Length );
a.DefaultAttributeValue = a.AttributeValue = new Variant( encoded.ToString() );
//StringBuilder stringBuilder = new StringBuilder();
//for( int index = 0; index < bytes.Length; index++ )
//{
// stringBuilder.Append( (char)bytes[ index ] );
//}
//a.DefaultAttributeValue = a.AttributeValue = new Variant( stringBuilder.ToString() );
}
break;
}
case BuiltInType.NodeId:
case BuiltInType.ExpandedNodeId:
{
NodeId nodeId = null;
ExpandedNodeId expandedNodeId = null;
if( val.TypeInfo.BuiltInType == BuiltInType.NodeId )
{
nodeId = val.Value as NodeId;
}
else
{
expandedNodeId = val.Value as ExpandedNodeId;
nodeId = ExpandedNodeId.ToNodeId( expandedNodeId, m_modelManager.NamespaceUris);
}
if ( nodeId != null )
{
a.DefaultAttributeValue = a.AttributeValue = nodeId;
AttributeType rootNodeId = a.Attribute[ "RootNodeId" ];
if ( rootNodeId != null )
{
AttributeType namespaceUri = rootNodeId.Attribute[ "NamespaceUri" ];
if ( namespaceUri != null )
{
namespaceUri.Value = m_modelManager.ModelNamespaceIndexes[ nodeId.NamespaceIndex ].NamespaceUri;
}
switch( nodeId.IdType )
{
case IdType.Numeric:
{
AttributeType id = rootNodeId.Attribute[ "NumericId" ];
id.Value = nodeId.Identifier.ToString();
break;
}
case IdType.String:
{
AttributeType id = rootNodeId.Attribute[ "StringId" ];
id.Value = nodeId.Identifier.ToString();
break;
}
case IdType.Guid:
{
AttributeType id = rootNodeId.Attribute[ "GuidId" ];
id.Value = nodeId.Identifier.ToString();
break;
}
case IdType.Opaque:
{
byte[] bytes = nodeId.Identifier as byte[];
if( bytes != null )
{
AttributeType id = rootNodeId.Attribute[ "OpaqueId" ];
string encoded = Convert.ToBase64String(
bytes, 0, bytes.Length );
id.Value = encoded;
}
break;
}
}
}
a.DefaultValue = null;
a.Value = null;
MinimizeNodeId( a );
}
if ( expandedNodeId != null )
{
if ( expandedNodeId.ServerIndex > 0 )
{
if( expandedNodeId.ServerIndex < m_modelManager.ModelNamespaceIndexes.Count )
{
string serverUri = m_modelManager.ModelNamespaceIndexes[ (int)expandedNodeId.ServerIndex ].NamespaceUri;
AttributeType serverInstanceUri = a.Attribute[ "ServerInstanceUri" ];
if ( serverInstanceUri != null )
{
serverInstanceUri.Value = serverUri;
}
}
}
}
break;
}
case BuiltInType.StatusCode:
{
StatusCode statusCode = (StatusCode)val.Value;
a.DefaultAttributeValue = a.AttributeValue = statusCode.Code;
break;
}
case BuiltInType.QualifiedName:
{
a.DefaultAttributeValue = a.AttributeValue = val;
QualifiedName qualifiedName = val.Value as QualifiedName;
if( qualifiedName != null )
{
AttributeType uri = a.Attribute[ "NamespaceURI" ];
uri.Value = m_modelManager.ModelNamespaceIndexes[ qualifiedName.NamespaceIndex ].NamespaceUri;
AttributeType nameAttribute = a.Attribute[ "Name" ];
nameAttribute.Value = qualifiedName.Name;
a.DefaultValue = null;
a.Value = null;
}
break;
}
case BuiltInType.LocalizedText:
{
Opc.Ua.LocalizedText localizedText = (Opc.Ua.LocalizedText)val.Value;
if( localizedText != null && localizedText.Text != null )
{
a.DefaultAttributeValue = a.AttributeValue = localizedText.Text;
}
break;
}
case BuiltInType.ExtensionObject:
{
ExtensionObject extensionObject = val.Value as ExtensionObject;
if ( extensionObject != null && extensionObject.Body != null )
{
AddModifyExtensionObject( a, extensionObject );
}
break;
}
case BuiltInType.DataValue:
{
DataValue dataValue = val.Value as DataValue;
if( dataValue != null )
{
Variant actualValue = new Variant( dataValue.Value );
NodeId dataTypeNodeId = Opc.Ua.TypeInfo.GetDataTypeId( actualValue.Value );
bool actualListOf = actualValue.TypeInfo.ValueRank >= ValueRanks.OneDimension;
AddModifyAttribute( a.Attribute, "Value", dataTypeNodeId, actualValue, actualListOf );
AddModifyAttribute( a.Attribute, "StatusCode", "StatusCode",
dataValue.StatusCode );
AddModifyAttribute( a.Attribute, "SourceTimestamp", "DateTime",
dataValue.SourceTimestamp );
if( dataValue.SourcePicoseconds > 0 )
{
AddModifyAttribute( a.Attribute, "SourcePicoseconds", "UInt16",
dataValue.SourcePicoseconds );
}
AddModifyAttribute( a.Attribute, "ServerTimestamp", "DateTime",
dataValue.ServerTimestamp );
if ( dataValue.ServerPicoseconds > 0 )
{
AddModifyAttribute( a.Attribute, "ServerPicoseconds", "UInt16",
dataValue.ServerPicoseconds );
}
}
break;
}
case BuiltInType.Variant:
{
Variant internalVariant = new Variant( val.Value );
NodeId dataTypeNodeId = Opc.Ua.TypeInfo.GetDataTypeId( internalVariant.Value );
bool internalListOf = internalVariant.TypeInfo.ValueRank >= ValueRanks.OneDimension;
AddModifyAttribute( a.Attribute, "Value", dataTypeNodeId, internalVariant, internalListOf );
break;
}
case BuiltInType.DiagnosticInfo:
{
AddModifyAttributeObject( a, val.Value );
break;
}
default:
handled = false;
break;
}
if ( handled && refDataType.Equals( "BaseDataType" ) )
{
// this is specifically the variant case
NodeId dataTypeFromBase = new NodeId( (uint)val.TypeInfo.BuiltInType );
string variantDataType = GetAttributeDataType( dataTypeFromBase );
a.AttributeDataType = variantDataType;
}
}
}
return a;
}
private bool MinimizeNodeId( AttributeType nodeIdAttribute )
{
bool minimized = false;
AttributeType rootNodeId = nodeIdAttribute.Attribute[ "RootNodeId" ];