This repository has been archived by the owner on Mar 25, 2024. It is now read-only.
forked from WilliamBerryiii/OPCUA2AAS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StationNodeManager.cs
451 lines (386 loc) · 18.3 KB
/
StationNodeManager.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
using Opc.Ua.Export;
using Opc.Ua.Server;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
using System.Net.Mime;
using System.Text;
using System.Threading;
namespace Opc.Ua.Sample
{
public enum StationStatus : int
{
Ready = 0,
WorkInProgress = 1,
Fault = 2
}
public class StationNodeManager : CustomNodeManager2
{
private Timer m_stationClock;
private ulong m_overallRunningTime = 0;
private ulong m_faultyTime = 0;
private ulong m_idealCycleTime = 5000;
private ulong m_actualCycleTime = 5000;
private StationStatus m_status = StationStatus.Ready;
private ulong m_energyConsumption = 1000;
private ulong m_pressure = 1000;
private ulong m_productSerialNumber = 1;
private ulong m_numberOfManufacturedProducts = 1;
private ulong m_numberOfDiscardedProducts = 0;
private ushort m_namespaceIndex;
private long m_lastUsedId;
private NodeId m_NumberOfManufacturedProductsID;
private NodeId m_NumberOfDiscardedProductsID;
private NodeId m_ProductSerialNumberID;
private NodeId m_ActualCycleTimeID;
private NodeId m_EnergyConsumptionID;
private NodeId m_FaultyTimeID;
private NodeId m_IdealCycleTimeID;
private NodeId m_OverallRunningTimeID;
private NodeId m_PressureID;
private NodeId m_StatusID;
public StationNodeManager(IServerInternal server, ApplicationConfiguration configuration)
: base(server, configuration)
{
SystemContext.NodeIdFactory = this;
using (Stream stream = new FileStream("Station.NodeSet2.xml", FileMode.Open))
{
UANodeSet nodeSet = UANodeSet.Read(stream);
NamespaceUris = nodeSet.NamespaceUris;
}
m_namespaceIndex = (ushort)(Server.NamespaceUris.Count - 1);
m_lastUsedId = 0;
m_stationClock = new Timer(Tick, this, Timeout.Infinite, (int)m_actualCycleTime);
}
public override NodeId New(ISystemContext context, NodeState node)
{
uint id = Utils.IncrementIdentifier(ref m_lastUsedId);
return new NodeId(id, m_namespaceIndex);
}
private FolderState CreateFolder(NodeState parent, string path, string name)
{
FolderState folder = new FolderState(parent)
{
SymbolicName = name,
ReferenceTypeId = ReferenceTypes.Organizes,
TypeDefinitionId = ObjectTypeIds.FolderType,
NodeId = new NodeId(path, NamespaceIndex),
BrowseName = new QualifiedName(path, NamespaceIndex),
DisplayName = new LocalizedText("en", name),
WriteMask = AttributeWriteMask.None,
UserWriteMask = AttributeWriteMask.None,
EventNotifier = EventNotifiers.None
};
parent?.AddChild(folder);
return folder;
}
private MethodState CreateMethod(NodeState parent, string path, string name)
{
MethodState method = new MethodState(parent)
{
SymbolicName = name,
ReferenceTypeId = ReferenceTypeIds.HasComponent,
NodeId = new NodeId(path, NamespaceIndex),
BrowseName = new QualifiedName(path, NamespaceIndex),
DisplayName = new LocalizedText("en", name),
WriteMask = AttributeWriteMask.None,
UserWriteMask = AttributeWriteMask.None,
Executable = true,
UserExecutable = true
};
parent?.AddChild(method);
return method;
}
public override void CreateAddressSpace(IDictionary<NodeId, IList<IReference>> externalReferences)
{
lock (Lock)
{
IList<IReference> references = null;
if (!externalReferences.TryGetValue(ObjectIds.ObjectsFolder, out references))
{
externalReferences[ObjectIds.ObjectsFolder] = references = new List<IReference>();
}
ImportNodeset2Xml(externalReferences, "Station.NodeSet2.xml");
FolderState root = CreateFolder(null, "AssetAdminShell", "AssetAdminShell");
root.AddReference(ReferenceTypes.Organizes, true, ObjectIds.ObjectsFolder);
references.Add(new NodeStateReference(ReferenceTypes.Organizes, false, root.NodeId));
root.EventNotifier = EventNotifiers.SubscribeToEvents;
AddRootNotifier(root);
MethodState createAASMethod = CreateMethod(root, "GenerateAAS", "GenerateAAS");
createAASMethod.OnCallMethod = new GenericMethodCalledEventHandler(OnGenerateAASCall);
AddPredefinedNode(SystemContext, root);
AddReverseReferences(externalReferences);
}
}
private ServiceResult OnGenerateAASCall(ISystemContext context, MethodState method, IList<object> inputArguments, IList<object> outputArguments)
{
try
{
string packagePath = Path.Combine(Directory.GetCurrentDirectory(), "Station.aasx");
using (Package package = Package.Open(packagePath, FileMode.Create))
{
// add package origin part
PackagePart origin = package.CreatePart(new Uri("/aasx/aasx-origin", UriKind.Relative), MediaTypeNames.Text.Plain, CompressionOption.Maximum);
using (Stream fileStream = origin.GetStream(FileMode.Create))
{
var bytes = Encoding.ASCII.GetBytes("Intentionally empty.");
fileStream.Write(bytes, 0, bytes.Length);
}
package.CreateRelationship(origin.Uri, TargetMode.Internal, "http://www.admin-shell.io/aasx/relationships/aasx-origin");
// add package spec part
PackagePart spec = package.CreatePart(new Uri("/aasx/aasenv-with-no-id/aasenv-with-no-id.aas.xml", UriKind.Relative), MediaTypeNames.Text.Xml);
string packageSpecPath = Path.Combine(Directory.GetCurrentDirectory(), "aasenv-with-no-id.aas.xml");
using (FileStream fileStream = new FileStream(packageSpecPath, FileMode.Open, FileAccess.Read))
{
CopyStream(fileStream, spec.GetStream());
}
origin.CreateRelationship(spec.Uri, TargetMode.Internal, "http://www.admin-shell.io/aasx/relationships/aas-spec");
// add the nodeset2.xml as a supplemental document part
PackagePart supplementalDoc = package.CreatePart(new Uri("/aasx/Station.NodeSet2.xml", UriKind.Relative), MediaTypeNames.Text.Xml);
string documentPath = Path.Combine(Directory.GetCurrentDirectory(), "Station.NodeSet2.xml");
using (FileStream fileStream = new FileStream(documentPath, FileMode.Open, FileAccess.Read))
{
CopyStream(fileStream, supplementalDoc.GetStream());
}
package.CreateRelationship(supplementalDoc.Uri, TargetMode.Internal, "http://www.admin-shell.io/aasx/relationships/aas-suppl");
}
return ServiceResult.Good;
}
catch (Exception ex)
{
return ServiceResult.Create(ex, StatusCodes.BadUnexpectedError, "Failed to create Asset Admin Shell!");
}
}
private void CopyStream(Stream source, Stream target)
{
const int bufSize = 0x1000;
byte[] buf = new byte[bufSize];
int bytesRead = 0;
while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
{
target.Write(buf, 0, bytesRead);
}
}
private void ImportNodeset2Xml(IDictionary<NodeId, IList<IReference>> externalReferences, string resourcepath)
{
using (Stream stream = new FileStream(resourcepath, FileMode.Open))
{
UANodeSet nodeSet = UANodeSet.Read(stream);
NodeStateCollection predefinedNodes = new NodeStateCollection();
nodeSet.Import(SystemContext, predefinedNodes);
for (int i = 0; i < predefinedNodes.Count; i++)
{
AddPredefinedNode(SystemContext, predefinedNodes[i]);
}
}
}
protected override NodeState AddBehaviourToPredefinedNode(ISystemContext context, NodeState predefinedNode)
{
// add behaviour to our methods
MethodState methodState = predefinedNode as MethodState;
if (methodState != null)
{
if (methodState.DisplayName == "Execute")
{
methodState.OnCallMethod = new GenericMethodCalledEventHandler(Execute);
// define the method's input argument (the serial number)
methodState.InputArguments = new PropertyState<Argument[]>(methodState)
{
NodeId = new NodeId(methodState.BrowseName.Name + "InArgs", NamespaceIndex),
BrowseName = BrowseNames.InputArguments
};
methodState.InputArguments.DisplayName = methodState.InputArguments.BrowseName.Name;
methodState.InputArguments.TypeDefinitionId = VariableTypeIds.PropertyType;
methodState.InputArguments.ReferenceTypeId = ReferenceTypeIds.HasProperty;
methodState.InputArguments.DataType = DataTypeIds.Argument;
methodState.InputArguments.ValueRank = ValueRanks.OneDimension;
methodState.InputArguments.Value = new Argument[]
{
new Argument { Name = "SerialNumber", Description = "Serial number of the product to make.", DataType = DataTypeIds.UInt64, ValueRank = ValueRanks.Scalar }
};
return predefinedNode;
}
if (methodState.DisplayName == "Reset")
{
methodState.OnCallMethod = new GenericMethodCalledEventHandler(Reset);
return predefinedNode;
}
if (methodState.DisplayName == "OpenPressureReleaseValve")
{
methodState.OnCallMethod = new GenericMethodCalledEventHandler(OpenPressureReleaseValve);
return predefinedNode;
}
}
// also capture the nodeIDs of our instance variables (i.e. NOT the model!)
BaseDataVariableState variableState = predefinedNode as BaseDataVariableState;
if ((variableState != null) && (variableState.ModellingRuleId == null))
{
if (variableState.DisplayName == "NumberOfManufacturedProducts")
{
m_NumberOfManufacturedProductsID = variableState.NodeId;
}
if (variableState.DisplayName == "NumberOfDiscardedProducts")
{
m_NumberOfDiscardedProductsID = variableState.NodeId;
}
if (variableState.DisplayName == "ProductSerialNumber")
{
m_ProductSerialNumberID = variableState.NodeId;
}
if (variableState.DisplayName == "ActualCycleTime")
{
m_ActualCycleTimeID = variableState.NodeId;
}
if (variableState.DisplayName == "EnergyConsumption")
{
m_EnergyConsumptionID = variableState.NodeId;
}
if (variableState.DisplayName == "FaultyTime")
{
m_FaultyTimeID = variableState.NodeId;
}
if (variableState.DisplayName == "IdealCycleTime")
{
m_IdealCycleTimeID = variableState.NodeId;
}
if (variableState.DisplayName == "OverallRunningTime")
{
m_OverallRunningTimeID = variableState.NodeId;
}
if (variableState.DisplayName == "Pressure")
{
m_PressureID = variableState.NodeId;
}
if (variableState.DisplayName == "Status")
{
m_StatusID = variableState.NodeId;
}
}
return predefinedNode;
}
private ServiceResult Execute(ISystemContext context, MethodState method, IList<object> inputArguments, IList<object> outputArguments)
{
if (m_status == StationStatus.Fault)
{
ServiceResult result = new ServiceResult(new Exception("Machine is in fault state, call reset first!"));
return result;
}
m_productSerialNumber = (ulong)inputArguments[0];
m_status = StationStatus.WorkInProgress;
m_stationClock.Change((int)m_actualCycleTime, (int)m_actualCycleTime);
return ServiceResult.Good;
}
private ServiceResult Reset(ISystemContext context, MethodState method, IList<object> inputArguments, IList<object> outputArguments)
{
m_status = StationStatus.Ready;
return ServiceResult.Good;
}
private ServiceResult OpenPressureReleaseValve(ISystemContext context, MethodState method, IList<object> inputArguments, IList<object> outputArguments)
{
m_pressure = 1000;
return ServiceResult.Good;
}
private void UpdateVariables()
{
NodeState node = Find(m_NumberOfManufacturedProductsID);
BaseDataVariableState variableState = node as BaseDataVariableState;
if (variableState != null)
{
variableState.Value = m_numberOfManufacturedProducts;
variableState.ClearChangeMasks(SystemContext, false);
}
node = Find(m_NumberOfDiscardedProductsID);
variableState = node as BaseDataVariableState;
if (variableState != null)
{
variableState.Value = m_numberOfDiscardedProducts;
variableState.ClearChangeMasks(SystemContext, false);
}
node = Find(m_ProductSerialNumberID);
variableState = node as BaseDataVariableState;
if (variableState != null)
{
variableState.Value = m_productSerialNumber;
variableState.ClearChangeMasks(SystemContext, false);
}
node = Find(m_ActualCycleTimeID);
variableState = node as BaseDataVariableState;
if (variableState != null)
{
variableState.Value = m_actualCycleTime;
variableState.ClearChangeMasks(SystemContext, false);
}
node = Find(m_EnergyConsumptionID);
variableState = node as BaseDataVariableState;
if (variableState != null)
{
variableState.Value = m_energyConsumption;
variableState.ClearChangeMasks(SystemContext, false);
}
node = Find(m_FaultyTimeID);
variableState = node as BaseDataVariableState;
if (variableState != null)
{
variableState.Value = m_faultyTime;
variableState.ClearChangeMasks(SystemContext, false);
}
node = Find(m_IdealCycleTimeID);
variableState = node as BaseDataVariableState;
if (variableState != null)
{
variableState.Value = m_idealCycleTime;
variableState.ClearChangeMasks(SystemContext, false);
}
node = Find(m_OverallRunningTimeID);
variableState = node as BaseDataVariableState;
if (variableState != null)
{
variableState.Value = m_overallRunningTime;
variableState.ClearChangeMasks(SystemContext, false);
}
node = Find(m_PressureID);
variableState = node as BaseDataVariableState;
if (variableState != null)
{
variableState.Value = m_pressure;
variableState.ClearChangeMasks(SystemContext, false);
}
node = Find(m_StatusID);
variableState = node as BaseDataVariableState;
if (variableState != null)
{
variableState.Value = m_status;
variableState.ClearChangeMasks(SystemContext, false);
}
}
private static void Tick(object state)
{
StationNodeManager nodeManager = (StationNodeManager) state;
if (nodeManager.m_status == StationStatus.Fault)
{
return;
}
if (nodeManager.m_status == StationStatus.WorkInProgress)
{
// we produce a discarded product every 100 parts
// we go into fault mode every 1000 parts
if ((nodeManager.m_numberOfManufacturedProducts % 1000) == 0)
{
nodeManager.m_status = StationStatus.Fault;
}
else if ((nodeManager.m_numberOfManufacturedProducts % 100) == 0)
{
nodeManager.m_numberOfDiscardedProducts++;
nodeManager.m_productSerialNumber++;
}
else
{
nodeManager.m_numberOfManufacturedProducts++;
nodeManager.m_productSerialNumber++;
}
}
nodeManager.UpdateVariables();
}
}
}