/
UANodeManager.cs
833 lines (703 loc) · 37.2 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
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 Opc.Ua.WotCon;
using Serilog;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
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 WoTAssetConnectionManagementState _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("http://opcfoundation.org/UA/WoT-Con/");
BaseObjectState assetManagementPassiveNode = (BaseObjectState)FindPredefinedNode(new NodeId(WotCon.Objects.WoTAssetConnectionManagement, WoTConNamespaceIndex), typeof(BaseObjectState));
_assetManagement.Create(SystemContext, assetManagementPassiveNode);
MethodState createAssetPassiveNode = (MethodState)FindPredefinedNode(new NodeId(WotCon.Methods.WoTAssetConnectionManagement_CreateAsset, WoTConNamespaceIndex), typeof(MethodState));
_assetManagement.CreateAsset = new(null);
_assetManagement.CreateAsset.Create(SystemContext, createAssetPassiveNode);
_assetManagement.CreateAsset.OnCall = new CreateAssetMethodStateMethodCallHandler(OnCreateAsset);
BaseVariableState createAssetInputArgumentsPassiveNode = (BaseVariableState)FindPredefinedNode(new NodeId(WotCon.Variables.WoTAssetConnectionManagementType_CreateAsset_InputArguments, WoTConNamespaceIndex), typeof(BaseVariableState));
_assetManagement.CreateAsset.InputArguments = new(null);
_assetManagement.CreateAsset.InputArguments.Create(SystemContext, createAssetInputArgumentsPassiveNode);
BaseVariableState createAssetOutputArgumentsPassiveNode = (BaseVariableState)FindPredefinedNode(new NodeId(WotCon.Variables.WoTAssetConnectionManagementType_CreateAsset_OutputArguments, WoTConNamespaceIndex), typeof(BaseVariableState));
_assetManagement.CreateAsset.OutputArguments = new(null);
_assetManagement.CreateAsset.OutputArguments.Create(SystemContext, createAssetOutputArgumentsPassiveNode);
MethodState deleteAssetPassiveNode = (MethodState)FindPredefinedNode(new NodeId(WotCon.Methods.WoTAssetConnectionManagement_DeleteAsset, WoTConNamespaceIndex), typeof(MethodState));
_assetManagement.DeleteAsset = new(null);
_assetManagement.DeleteAsset.Create(SystemContext, deleteAssetPassiveNode);
_assetManagement.DeleteAsset.OnCall = new DeleteAssetMethodStateMethodCallHandler(OnDeleteAsset);
BaseVariableState deleteAssetInputArgumentsPassiveNode = (BaseVariableState)FindPredefinedNode(new NodeId(WotCon.Variables.WoTAssetConnectionManagementType_DeleteAsset_InputArguments, WoTConNamespaceIndex), typeof(BaseVariableState));
_assetManagement.DeleteAsset.InputArguments = new(null);
_assetManagement.DeleteAsset.InputArguments.Create(SystemContext, deleteAssetInputArgumentsPassiveNode);
// 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());
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());
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)
{
// do nothing
}
}
}
}
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 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();
}
IWoTAssetState asset = new IWoTAssetState(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(IWoTAssetState));
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);
string assetId = AssetConnectionTest(td, out byte unitId);
// create nodes for each TD property
foreach (KeyValuePair<string, Property> property in td.Properties)
{
foreach (object form in property.Value.Forms)
{
if (td.Base.ToLower().StartsWith("modbus+tcp://"))
{
AddNodeForModbusRegister(parent, property, form, assetId, unitId);
}
}
}
_ = Task.Factory.StartNew(UpdateNodeValues, assetId, TaskCreationOptions.LongRunning);
Log.Logger.Information($"Successfully parsed WoT file for asset: {assetId}");
}
private void AddNodeForModbusRegister(NodeState assetFolder, KeyValuePair<string, Property> property, object form, string assetId, byte unitId)
{
ModbusForm modbusForm = JsonConvert.DeserializeObject<ModbusForm>(form.ToString());
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 (((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;
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, complexTypeInstance));
}
}
else
{
// OPC UA type info not found, default to float
_uaVariables.Add(variableId, CreateVariable(assetFolder, variableName, new ExpandedNodeId(DataTypes.Float), assetFolder.NodeId.NamespaceIndex));
}
}
else
{
// it's an OPC UA built-in type
_uaVariables.Add(variableId, CreateVariable(assetFolder, variableName, new ExpandedNodeId(new NodeId(nodeID), namespaceURI), assetFolder.NodeId.NamespaceIndex));
}
}
else
{
// no namespace info, default to float
_uaVariables.Add(variableId, CreateVariable(assetFolder, variableName, new ExpandedNodeId(DataTypes.Float), assetFolder.NodeId.NamespaceIndex));
}
}
else
{
// can't parse type info, default to float
_uaVariables.Add(variableId, CreateVariable(assetFolder, variableName, new ExpandedNodeId(DataTypes.Float), assetFolder.NodeId.NamespaceIndex));
}
}
else
{
// no type info, default to float
_uaVariables.Add(variableId, CreateVariable(assetFolder, variableName, new ExpandedNodeId(DataTypes.Float), assetFolder.NodeId.NamespaceIndex));
}
// create an asset tag and add to our list
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
};
// check if we need to create a new asset first
if (!_tags.ContainsKey(assetId))
{
_tags.Add(assetId, new List<AssetTag>());
}
// add the tag to the asset
_tags[assetId].Add(tag);
}
private string AssetConnectionTest(ThingDescription td, out byte unitId)
{
unitId = 1;
IAsset assetInterface = null;
if (td.Base.ToLower().StartsWith("modbus+tcp://"))
{
string[] modbusAddress = td.Base.Split(new char[] { ':','/' });
if ((modbusAddress.Length != 6) && (modbusAddress[0] != "modbus+tcp"))
{
throw new Exception("Expected Modbus address in the format modbus+tcp://ipaddress:port/unitID!");
}
// check if we can reach the Modbus asset
unitId = byte.Parse(modbusAddress[5]);
ModbusTCPClient client = new();
client.Connect(modbusAddress[3], int.Parse(modbusAddress[4]));
assetInterface = client;
}
_assets.Add(td.Name, assetInterface);
return td.Name;
}
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, 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 LocalizedText("en", name),
WriteMask = AttributeWriteMask.None,
UserWriteMask = AttributeWriteMask.None,
AccessLevel = AccessLevels.CurrentRead,
DataType = ExpandedNodeId.ToNodeId(type, Server.NamespaceUris),
Value = value
};
parent?.AddChild(variable);
AddPredefinedNode(SystemContext, variable);
return variable;
}
private void UpdateNodeValues(object assetNameObject)
{
bool assetDeleted = false;
while (!_shutdown && !assetDeleted)
{
Thread.Sleep(1000);
_ticks++;
string assetId = (string)assetNameObject;
if (string.IsNullOrEmpty(assetId) || !_tags.ContainsKey(assetId) || !_assets.ContainsKey(assetId))
{
assetDeleted = true;
continue;
}
foreach (AssetTag tag in _tags[assetId])
{
try
{
if (_assets[assetId] is ModbusTCPClient)
{
if (_ticks * 1000 % tag.PollingInterval == 0)
{
ModbusTCPClient.FunctionCode functionCode = ModbusTCPClient.FunctionCode.ReadCoilStatus;
if (tag.Entity == "HoldingRegister")
{
functionCode = ModbusTCPClient.FunctionCode.ReadHoldingRegisters;
}
string[] addressParts = tag.Address.Split(new char[] { '?', '&', '=' });
if ((addressParts.Length == 3) && (addressParts[1] == "quantity"))
{
// read tag
byte unitID = tag.UnitID;
uint address = uint.Parse(addressParts[0]);
ushort quantity = ushort.Parse(addressParts[2]);
byte[] tagBytes = null;
try
{
tagBytes = _assets[assetId].Read(unitID, functionCode.ToString(), address, quantity).GetAwaiter().GetResult();
}
catch (Exception ex)
{
Log.Logger.Error(ex.Message, ex);
// try reconnecting
string[] remoteEndpoint = _assets[assetId].GetRemoteEndpoint().Split(':');
_assets[assetId].Disconnect();
_assets[assetId].Connect(remoteEndpoint[0], int.Parse(remoteEndpoint[1]));
}
if ((tagBytes != null) && (tag.Type == "Float"))
{
float value = BitConverter.ToSingle(ByteSwapper.Swap(tagBytes));
// check for complex type
if (_uaVariables[tag.Name].Value is ExtensionObject)
{
// decode existing values and re-encode them with our updated value
BinaryDecoder decoder = new((byte[])((ExtensionObject)_uaVariables[tag.Name].Value).Body, ServiceMessageContext.GlobalContext);
BinaryEncoder encoder = new(ServiceMessageContext.GlobalContext);
DataTypeState opcuaType = (DataTypeState)Find(_uaVariables[tag.Name].DataType);
if ((opcuaType != null) && ((StructureDefinition)opcuaType?.DataTypeDefinition?.Body).Fields?.Count > 0)
{
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":
{
float newValue = decoder.ReadFloat(field.Name);
if (field.Name == tag.MappedUAFieldPath)
{
// overwrite existing value with our upated value
newValue = value;
}
encoder.WriteFloat(field.Name, newValue);
break;
}
default: throw new NotImplementedException("Complex type field data type " + field.DataType.ToString() + " not yet supported!");
}
}
((ExtensionObject)_uaVariables[tag.Name].Value).Body = encoder.CloseAndReturnBuffer();
}
}
else
{
_uaVariables[tag.Name].Value = value;
}
_uaVariables[tag.Name].Timestamp = DateTime.UtcNow;
_uaVariables[tag.Name].ClearChangeMasks(SystemContext, false);
}
}
}
}
}
catch (Exception ex)
{
// skip this tag, but log an error
Log.Logger.Error(ex.Message, ex);
}
}
}
}
}
}