• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

WindhoverLabs / yamcs-opcua / #33

16 Jul 2024 05:37PM UTC coverage: 88.606%. Remained the same
#33

push

lorenzo-gomez-windhover
-Wait till all initialization is done for OPCUA_INIT_OK

1 of 1 new or added line in 1 file covered. (100.0%)

1 existing line in 1 file now uncovered.

661 of 746 relevant lines covered (88.61%)

0.89 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

88.39
/src/main/java/com/windhoverlabs/yamcs/opcua/OPCUALink.java
1
/****************************************************************************
2
 *
3
 *   Copyright (c) 2024 Windhover Labs, L.L.C. All rights reserved.
4
 *
5
 * Redistribution and use in source and binary forms, with or without
6
 * modification, are permitted provided that the following conditions
7
 * are met:
8
 *
9
 * 1. Redistributions of source code must retain the above copyright
10
 *    notice, this list of conditions and the following disclaimer.
11
 * 2. Redistributions in binary form must reproduce the above copyright
12
 *    notice, this list of conditions and the following disclaimer in
13
 *    the documentation and/or other materials provided with the
14
 *    distribution.
15
 * 3. Neither the name Windhover Labs nor the names of its
16
 *    contributors may be used to endorse or promote products derived
17
 *    from this software without specific prior written permission.
18
 *
19
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
22
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
23
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
25
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
26
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
27
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
29
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30
 * POSSIBILITY OF SUCH DAMAGE.
31
 *
32
 *****************************************************************************/
33

34
package com.windhoverlabs.yamcs.opcua;
35

36
import static com.google.common.collect.Lists.newArrayList;
37
import static org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint;
38
import static org.yamcs.xtce.NameDescription.qualifiedName;
39

40
import com.google.gson.JsonObject;
41
import java.io.BufferedWriter;
42
import java.io.IOException;
43
import java.nio.file.Files;
44
import java.nio.file.Paths;
45
import java.nio.file.StandardOpenOption;
46
import java.time.Instant;
47
import java.time.temporal.ChronoUnit;
48
import java.util.ArrayList;
49
import java.util.Arrays;
50
import java.util.HashMap;
51
import java.util.HashSet;
52
import java.util.List;
53
import java.util.Map;
54
import java.util.Objects;
55
import java.util.Set;
56
import java.util.concurrent.CompletableFuture;
57
import java.util.concurrent.ConcurrentHashMap;
58
import java.util.concurrent.ExecutionException;
59
import java.util.concurrent.atomic.AtomicLong;
60
import java.util.function.Supplier;
61
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
62
import org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfig;
63
import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaMonitoredItem;
64
import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription;
65
import org.eclipse.milo.opcua.sdk.client.nodes.UaNode;
66
import org.eclipse.milo.opcua.sdk.client.subscriptions.ManagedDataItem;
67
import org.eclipse.milo.opcua.sdk.client.subscriptions.ManagedSubscription;
68
import org.eclipse.milo.opcua.stack.client.DiscoveryClient;
69
import org.eclipse.milo.opcua.stack.core.AttributeId;
70
import org.eclipse.milo.opcua.stack.core.Identifiers;
71
import org.eclipse.milo.opcua.stack.core.UaException;
72
import org.eclipse.milo.opcua.stack.core.types.builtin.ByteString;
73
import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
74
import org.eclipse.milo.opcua.stack.core.types.builtin.DateTime;
75
import org.eclipse.milo.opcua.stack.core.types.builtin.ExtensionObject;
76
import org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText;
77
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
78
import org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName;
79
import org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode;
80
import org.eclipse.milo.opcua.stack.core.types.builtin.Variant;
81
import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger;
82
import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UShort;
83
import org.eclipse.milo.opcua.stack.core.types.enumerated.IdType;
84
import org.eclipse.milo.opcua.stack.core.types.enumerated.MonitoringMode;
85
import org.eclipse.milo.opcua.stack.core.types.enumerated.NodeClass;
86
import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn;
87
import org.eclipse.milo.opcua.stack.core.types.structured.BrowsePath;
88
import org.eclipse.milo.opcua.stack.core.types.structured.BrowsePathResult;
89
import org.eclipse.milo.opcua.stack.core.types.structured.ContentFilter;
90
import org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription;
91
import org.eclipse.milo.opcua.stack.core.types.structured.EventFilter;
92
import org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemCreateRequest;
93
import org.eclipse.milo.opcua.stack.core.types.structured.MonitoringParameters;
94
import org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId;
95
import org.eclipse.milo.opcua.stack.core.types.structured.RelativePath;
96
import org.eclipse.milo.opcua.stack.core.types.structured.RelativePathElement;
97
import org.eclipse.milo.opcua.stack.core.types.structured.SimpleAttributeOperand;
98
import org.eclipse.milo.opcua.stack.core.types.structured.TranslateBrowsePathsToNodeIdsResponse;
99
import org.slf4j.Logger;
100
import org.slf4j.LoggerFactory;
101
import org.yamcs.ConfigurationException;
102
import org.yamcs.Spec;
103
import org.yamcs.Spec.OptionType;
104
import org.yamcs.StandardTupleDefinitions;
105
import org.yamcs.ValidationException;
106
import org.yamcs.YConfiguration;
107
import org.yamcs.YamcsServer;
108
import org.yamcs.http.NotFoundException;
109
import org.yamcs.mdb.XtceAssembler;
110
import org.yamcs.parameter.ParameterValue;
111
import org.yamcs.parameter.SystemParametersProducer;
112
import org.yamcs.parameter.SystemParametersService;
113
import org.yamcs.protobuf.Event.EventSeverity;
114
import org.yamcs.protobuf.Yamcs.NamedObjectId;
115
import org.yamcs.protobuf.Yamcs.Value.Type;
116
import org.yamcs.tctm.AbstractLink;
117
import org.yamcs.tctm.Link;
118
import org.yamcs.tctm.LinkAction;
119
import org.yamcs.utils.ValueUtility;
120
import org.yamcs.xtce.BooleanParameterType;
121
import org.yamcs.xtce.EnumeratedParameterType;
122
import org.yamcs.xtce.FloatParameterType;
123
import org.yamcs.xtce.IntegerParameterType;
124
import org.yamcs.xtce.NameDescription;
125
import org.yamcs.xtce.Parameter;
126
import org.yamcs.xtce.ParameterType;
127
import org.yamcs.xtce.SpaceSystem;
128
import org.yamcs.xtce.StringParameterType;
129
import org.yamcs.xtce.XtceDb;
130
import org.yamcs.yarch.DataType;
131
import org.yamcs.yarch.Stream;
132
import org.yamcs.yarch.Tuple;
133
import org.yamcs.yarch.TupleDefinition;
134
import org.yamcs.yarch.YarchDatabase;
135
import org.yamcs.yarch.YarchDatabaseInstance;
136
import org.yamcs.yarch.protobuf.Db.Event;
137

138
/**
139
 * Implementation of the OPCUA protocol as a YAMCS link. Maps configured nodes(see docs for details)
140
 * to yamcs PVs and subscribes to OPCUA variables for realtime updates.
141
 *
142
 * @author Lorenzo Gomez
143
 */
144
public class OPCUALink extends AbstractLink implements Runnable, SystemParametersProducer {
1✔
145

146
  class NodeIDAttrPair {
147
    NodeId nodeID;
148
    AttributeId attrID;
149

150
    public NodeIDAttrPair(NodeId newNodeID, AttributeId newAttrID) {
1✔
151
      this.nodeID = newNodeID;
1✔
152
      this.attrID = newAttrID;
1✔
153
    }
1✔
154

155
    public int hashCode() {
156
      return Objects.hash(this.nodeID, this.attrID);
1✔
157
    }
158

159
    public boolean equals(Object obj) {
160
      return (this.hashCode() == obj.hashCode());
1✔
161
    }
162
  }
163

164
  class NodePath {
1✔
165
    String path;
166
    HashMap<Object, Object> rootNodeID = new HashMap<Object, Object>();
1✔
167
  }
168

169
  /** Useful status for tracking initialization status of the link. */
170
  public enum OPCUAINITStatus {
1✔
171
    OPCUA_INIT_CONFIG,
1✔
172
    OPCUA_INIT_TREE,
1✔
173
    OPCUA_INIT_TREE_FAILED,
1✔
174
    OPCUA_INIT_GENERATE_XTCE,
1✔
175
    OPCUA_INIT_EVENTS,
1✔
176
    OPCUA_INIT_DATA_SUBSCRIPTION,
1✔
177
    OPCUA_INIT_ALL_DATA_QUERY,
1✔
178
    OPCUA_INIT_OK
1✔
179
  }
180

181
  /* Configuration Defaults */
182
  static final String STREAM_NAME = "opcua_params";
183

184
  /* Internal member attributes. */
185
  protected Thread thread;
186
  private String opcuaStreamName;
187
  private String parametersNamespace;
188
  XtceDb mdb;
189
  Stream opcuaStream;
190
  private static TupleDefinition gftdef = StandardTupleDefinitions.PARAMETER.copy();
1✔
191
  private ManagedSubscription opcuaSubscription;
192

193
  private static final Logger internalLogger = LoggerFactory.getLogger(OPCUALink.class.getName());
1✔
194

195
  /**
196
   * @note ALWAYS re-use params as org.yamcs.parameter.ParameterRequestManager.param2RequestMap uses
197
   *     the object inside a map that was added to the mdb for the very fist time. If when
198
   *     publishing the PV, we create a new VariableParam object clients will NOT receive real-time
199
   *     updates as the new object VariableParam inside the new PV won't match the one inside
200
   *     org.yamcs.parameter.ParameterRequestManager.param2RequestMap since the object hashes do not
201
   *     match (since VariableParam does not override its hash function).
202
   */
203
  private ConcurrentHashMap<NodeIDAttrPair, VariableParam> nodeIDToParamsMap =
1✔
204
      new ConcurrentHashMap<NodeIDAttrPair, VariableParam>();
205

206
  private OpcUaClient client;
207

208
  protected AtomicLong inCount = new AtomicLong(0);
1✔
209

210
  private Status linkStatus = Status.OK;
1✔
211

212
  /* Configuration Parameters */
213

214
  private String discoverURL;
215
  private String endpointURL;
216
  private boolean queryAllNodesAtStartup;
217
  private String outputFile;
218
  private int publishInterval; // milliseconds
219

220
  private ArrayList<NodePath> relativeNodePaths = new ArrayList<NodePath>();
1✔
221

222
  private final AtomicLong clientHandles = new AtomicLong(1L);
1✔
223

224
  /* System parameters*/
225

226
  private Parameter OPCUAStatusParam;
227
  private OPCUAINITStatus currentOPCUAStatus;
228
  private Parameter OPCUAActiveSubsParam;
229
  private AtomicLong OPCUAActiveSubs = new AtomicLong(0);
1✔
230

231
  LinkAction startAction =
1✔
232
      new LinkAction("query_all", "Query All OPCUA Server Data") {
1✔
233
        @Override
234
        public JsonObject execute(Link link, JsonObject jsonObject) {
235

236
          internalLogger.info("Executing query_all action");
1✔
237
          CompletableFuture.supplyAsync(
1✔
238
                  (Supplier<Integer>)
239
                      () -> {
240
                        queryAllOPCUAData();
1✔
241

242
                        return 0;
1✔
243
                      })
244
              .whenComplete(
1✔
245
                  (vaue, e) -> {
246
                    internalLogger.info("query_all action Complete");
1✔
247
                  });
1✔
248

249
          return jsonObject;
1✔
250
        }
251
      };
252

253
  public OPCUAINITStatus getCurrentOPCUAStatus() {
254
    return currentOPCUAStatus;
1✔
255
  }
256

257
  @Override
258
  public Spec getSpec() {
259
    Spec spec = new Spec();
1✔
260

261
    /* Define our configuration parameters. */
262
    spec.addOption("name", OptionType.STRING).withRequired(true);
1✔
263
    spec.addOption("class", OptionType.STRING).withRequired(true);
1✔
264
    spec.addOption("opcuaStream", OptionType.STRING).withRequired(true);
1✔
265
    spec.addOption("endpointUrl", OptionType.STRING).withRequired(true);
1✔
266
    spec.addOption("discoveryUrl", OptionType.STRING).withRequired(true);
1✔
267
    spec.addOption("xtceOutputFile", OptionType.STRING).withRequired(true);
1✔
268
    spec.addOption("parametersNamespace", OptionType.STRING).withRequired(true);
1✔
269
    spec.addOption("publishInterval", OptionType.INTEGER).withRequired(true);
1✔
270
    spec.addOption("queryAllNodesAtStartup", OptionType.BOOLEAN).withRequired(false);
1✔
271

272
    Spec rootNodeIDSpec = new Spec();
1✔
273

274
    rootNodeIDSpec.addOption("namespaceIndex", OptionType.INTEGER).withRequired(true);
1✔
275
    rootNodeIDSpec.addOption("identifier", OptionType.STRING).withRequired(true);
1✔
276
    rootNodeIDSpec.addOption("identifierType", OptionType.STRING).withRequired(true);
1✔
277

278
    Spec nodePathSpec = new Spec();
1✔
279
    nodePathSpec.addOption("path", OptionType.STRING);
1✔
280
    nodePathSpec
1✔
281
        .addOption("rootNodeID", OptionType.MAP)
1✔
282
        .withRequired(true)
1✔
283
        .withSpec(rootNodeIDSpec);
1✔
284

285
    spec.addOption("nodePaths", OptionType.LIST)
1✔
286
        .withElementType(OptionType.MAP)
1✔
287
        .withRequired(true)
1✔
288
        .withSpec(nodePathSpec);
1✔
289

290
    return spec;
1✔
291
  }
292

293
  @Override
294
  public void init(String yamcsInstance, String serviceName, YConfiguration config)
295
      throws ConfigurationException {
296
    super.init(yamcsInstance, serviceName, config);
1✔
297

298
    /* Local variables */
299
    this.config = config;
1✔
300
    /* Validate the configuration that the user passed us. */
301
    try {
302
      config = getSpec().validate(config);
1✔
303
    } catch (ValidationException e) {
×
304
      log.error("Failed configuration validation.", e);
×
305
      notifyFailed(e);
×
306
    }
1✔
307
    YarchDatabaseInstance ydb = YarchDatabase.getInstance(yamcsInstance);
1✔
308

309
    this.opcuaStreamName = config.getString("opcuaStream");
1✔
310
    this.opcuaStream = getStream(ydb, opcuaStreamName);
1✔
311
    this.parametersNamespace = config.getString("parametersNamespace");
1✔
312
    this.mdb = YamcsServer.getServer().getInstance(yamcsInstance).getXtceDb();
1✔
313

314
    readOPCUAConfig(config);
1✔
315
    readNodePathsConfig(config);
1✔
316

317
    outputFile = config.getString("xtceOutputFile");
1✔
318
  }
1✔
319

320
  private void readOPCUAConfig(YConfiguration config) {
321
    this.endpointURL = config.getString("endpointUrl");
1✔
322
    this.discoverURL = config.getString("discoveryUrl");
1✔
323
    this.publishInterval = config.getInt("publishInterval");
1✔
324
    this.queryAllNodesAtStartup = config.getBoolean("queryAllNodesAtStartup", false);
1✔
325
  }
1✔
326

327
  private void readNodePathsConfig(YConfiguration config) {
328
    List<Map<Object, Object>> nodePaths = config.getList("nodePaths");
1✔
329

330
    for (Map<Object, Object> path : nodePaths) {
1✔
331
      NodePath nodePath = new NodePath();
1✔
332
      nodePath.path = (String) path.get("path");
1✔
333
      nodePath.rootNodeID = (HashMap<Object, Object>) path.get("rootNodeID");
1✔
334
      relativeNodePaths.add(nodePath);
1✔
335
    }
1✔
336
  }
1✔
337

338
  private static SpaceSystem verifySpaceSystem(XtceDb mdb, String pathName) {
339
    String namespace;
340
    String name;
341
    int lastSlash = pathName.lastIndexOf('/');
1✔
342
    if ("/".equals(pathName)) {
1✔
343
      namespace = "";
×
344
      name = "";
×
345
    } else if (lastSlash == -1 || lastSlash == pathName.length() - 1) {
1✔
346
      namespace = "";
×
347
      name = pathName;
×
348
    } else {
349
      namespace = pathName.substring(0, lastSlash);
1✔
350
      name = pathName.substring(lastSlash + 1);
1✔
351
    }
352

353
    // First try with a prefixed slash (should be the common case)
354
    NamedObjectId id =
355
        NamedObjectId.newBuilder().setNamespace("/" + namespace).setName(name).build();
1✔
356
    SpaceSystem spaceSystem = mdb.getSpaceSystem(id);
1✔
357
    if (spaceSystem != null) {
1✔
358
      return spaceSystem;
×
359
    }
360

361
    // Maybe some non-xtce namespace like MDB:OPS Name
362
    id = NamedObjectId.newBuilder().setNamespace(namespace).setName(name).build();
1✔
363
    spaceSystem = mdb.getSpaceSystem(id);
1✔
364
    if (spaceSystem != null) {
1✔
365
      return spaceSystem;
1✔
366
    }
367

368
    throw new NotFoundException("No such space system");
×
369
  }
370

371
  /**
372
   * Initializes all PV mappings to OPCUA nodes and realtime subscriptions(managed data items in
373
   * OPCUA terms).
374
   */
375
  private void opcuaInit() {
376
    try {
377

378
      currentOPCUAStatus = OPCUAINITStatus.OPCUA_INIT_TREE;
1✔
379
      browseOPCUATree(client);
1✔
380
      currentOPCUAStatus = OPCUAINITStatus.OPCUA_INIT_GENERATE_XTCE;
1✔
381
      exportXTCE();
1✔
382
      currentOPCUAStatus = OPCUAINITStatus.OPCUA_INIT_EVENTS;
1✔
383
      subscribeToEvents(client);
1✔
384

385
    } catch (Exception e) {
1✔
386
      e.printStackTrace();
1✔
387
      currentOPCUAStatus = OPCUAINITStatus.OPCUA_INIT_TREE_FAILED;
1✔
388
      return;
1✔
389
    }
1✔
390
    try {
391
      currentOPCUAStatus = OPCUAINITStatus.OPCUA_INIT_DATA_SUBSCRIPTION;
1✔
392
      createOPCUASubscriptions();
1✔
393
    } catch (Exception e) {
×
394
      e.printStackTrace();
×
395
      return;
×
396
    }
1✔
397
    if (queryAllNodesAtStartup) {
1✔
UNCOV
398
      currentOPCUAStatus = OPCUAINITStatus.OPCUA_INIT_ALL_DATA_QUERY;
×
399
      queryAllOPCUAData();
×
400
    }
401

402
    currentOPCUAStatus = OPCUAINITStatus.OPCUA_INIT_OK;
1✔
403
  }
1✔
404

405
  private void exportXTCE() throws IOException {
406
    var spaceSystem = verifySpaceSystem(mdb, parametersNamespace);
1✔
407
    var xtce = new XtceAssembler().toXtce(mdb, spaceSystem.getQualifiedName(), fqn -> true);
1✔
408
    BufferedWriter writer = null;
1✔
409

410
    if (outputFile != null) {
1✔
411
      writer =
1✔
412
          Files.newBufferedWriter(
1✔
413
              Paths.get(outputFile),
1✔
414
              StandardOpenOption.CREATE,
415
              StandardOpenOption.TRUNCATE_EXISTING);
416

417
      writer.write(xtce);
1✔
418

419
      writer.flush();
1✔
420
      writer.close();
1✔
421
    }
422
  }
1✔
423

424
  private void opcuaClientConnect() throws Exception {
425
    client = configureClient();
1✔
426
    connectToOPCUAServer(client);
1✔
427
  }
1✔
428

429
  private static Stream getStream(YarchDatabaseInstance ydb, String streamName) {
430
    Stream stream = ydb.getStream(streamName);
1✔
431
    if (stream == null) {
1✔
432
      try {
433
        ydb.execute("create stream " + streamName + gftdef.getStringDefinition());
1✔
434
      } catch (Exception e) {
×
435
        throw new ConfigurationException(e);
×
436
      }
1✔
437

438
      stream = ydb.getStream(streamName);
1✔
439
    }
440
    return stream;
1✔
441
  }
442

443
  @Override
444
  public void doDisable() {
445
    /* If the thread is created, interrupt it. */
446
    if (thread != null) {
1✔
447
      thread.interrupt();
1✔
448
    }
449

450
    linkStatus = Status.DISABLED;
1✔
451
  }
1✔
452

453
  @Override
454
  public void doEnable() {
455
    linkStatus = Status.OK;
1✔
456
  }
1✔
457

458
  @Override
459
  public String getDetailedStatus() {
460
    if (isDisabled()) {
1✔
461
      return String.format("DISABLED");
1✔
462
    } else {
463
      return String.format("OK, received %d packets", inCount.get());
1✔
464
    }
465
  }
466

467
  @Override
468
  public Status connectionStatus() {
469
    return linkStatus;
1✔
470
  }
471

472
  @Override
473
  protected void doStart() {
474
    try {
475
      opcuaClientConnect();
1✔
476
    } catch (Exception e) {
×
477
      e.printStackTrace();
×
478
      linkStatus = Status.FAILED;
×
479
      notifyFailed(e);
×
480
      return;
×
481
    }
1✔
482
    if (!isDisabled()) {
1✔
483
      doEnable();
1✔
484
    }
485
    startAction.addChangeListener(
1✔
486
        () -> {
487
          /**
488
           * TODO:Might be useful if we want turn off any functionality when the action is disabled
489
           * for instance..
490
           */
491
        });
×
492

493
    /* Create and start the new thread. */
494
    thread = new Thread(this);
1✔
495
    thread.setName(this.getClass().getSimpleName() + "-" + linkName);
1✔
496
    thread.start();
1✔
497

498
    notifyStarted();
1✔
499
  }
1✔
500

501
  @Override
502
  protected void doStop() {
503
    try {
504
      client.disconnect().get();
1✔
505
    } catch (InterruptedException | ExecutionException e) {
×
506
      // TODO Auto-generated catch block
507
      e.printStackTrace();
×
508
    }
1✔
509
    if (thread != null) {
1✔
510
      thread.interrupt();
1✔
511
    }
512

513
    notifyStopped();
1✔
514
  }
1✔
515

516
  @Override
517
  public void run() {
518
    opcuaInit();
1✔
519
    /* Enter our main loop */
520
    while (isRunningAndEnabled()) {}
1✔
521
  }
1✔
522

523
  /**
524
   * Reads all attributes of all configured Value nodes and updates their corresponding PV. Useful
525
   * for querying data from the OPCUA server once, data such as browse names, NodeIds, etc.
526
   */
527
  private void queryAllOPCUAData() {
528
    TupleDefinition tdef = gftdef.copy();
1✔
529
    List<Object> cols = new ArrayList<>(4 + nodeIDToParamsMap.keySet().size());
1✔
530

531
    tdef = gftdef.copy();
1✔
532
    long gentime = timeService.getMissionTime();
1✔
533
    cols.add(gentime);
1✔
534
    cols.add(parametersNamespace);
1✔
535
    cols.add(0);
1✔
536
    cols.add(gentime);
1✔
537

538
    int columnCount = 0;
1✔
539

540
    Set<NodeId> nodeSet = new HashSet<NodeId>();
1✔
541
    /**
542
     * NOTE:This is super inefficient... The reason we collect these nodeIDs in a set is because
543
     * otherwise we will have redundant subscription(s) since there is more than 1 attribute per
544
     * nodeID given how nodeIDToParamsMap is designed
545
     */
546
    for (NodeIDAttrPair pair : nodeIDToParamsMap.keySet()) {
1✔
547
      nodeSet.add(pair.nodeID);
1✔
548
    }
1✔
549

550
    for (NodeId nId : nodeSet) {
1✔
551
      UaNode node;
552

553
      try {
554
        node = client.getAddressSpace().getNode(nId);
1✔
555

556
        DataValue nodeClass = node.readAttribute(AttributeId.NodeClass);
1✔
557

558
        switch (NodeClass.from((int) nodeClass.getValue().getValue())) {
1✔
559
          case Variable:
560
            for (AttributeId attr : AttributeId.VARIABLE_ATTRIBUTES) {
1✔
561
              VariableParam p = nodeIDToParamsMap.get(new NodeIDAttrPair(nId, attr));
1✔
562

563
              if (p.getParameterType() == null) {
1✔
564
                internalLogger.warn(
×
565
                    "{} ignored since it does not have a Parameter type",
566
                    p,
567
                    Character.toString(NameDescription.PATH_SEPARATOR));
×
568
                continue;
×
569
              }
570

571
              switch (p.getParameterType().getValueType()) {
1✔
572
                case BOOLEAN:
573
                  {
574
                    Boolean value = true;
1✔
575
                    if (node.readAttribute(attr).getValue().isNull()) {
1✔
576
                      //                      value = "NULL";
577
                    } else {
578
                      value = (Boolean) node.readAttribute(attr).getValue().getValue();
1✔
579
                    }
580

581
                    tdef.addColumn(p.getQualifiedName(), DataType.PARAMETER_VALUE);
1✔
582
                    cols.add(getPV(p, Instant.now().toEpochMilli(), value));
1✔
583
                  }
584
                  break;
1✔
585
                case DOUBLE:
586
                  {
587
                    Number value = 0;
1✔
588
                    if (node.readAttribute(attr).getValue().isNull()) {
1✔
589
                      internalLogger.warn("node {} has a Null variant.", node);
×
590
                    } else {
591
                      value = (Number) node.readAttribute(attr).getValue().getValue();
1✔
592
                    }
593

594
                    tdef.addColumn(p.getQualifiedName(), DataType.PARAMETER_VALUE);
1✔
595
                    cols.add(getPV(p, Instant.now().toEpochMilli(), value.doubleValue()));
1✔
596
                  }
597
                  break;
1✔
598
                case FLOAT:
599
                  {
600
                    Number value = 0;
1✔
601
                    if (node.readAttribute(attr).getValue().isNull()) {
1✔
602
                      internalLogger.warn("node {} has a Null variant.", node);
×
603
                    } else {
604
                      value = (Number) node.readAttribute(attr).getValue().getValue();
1✔
605
                    }
606

607
                    tdef.addColumn(p.getQualifiedName(), DataType.PARAMETER_VALUE);
1✔
608
                    cols.add(getPV(p, Instant.now().toEpochMilli(), value.floatValue()));
1✔
609
                  }
610
                  break;
1✔
611
                case SINT32:
612
                  {
613
                    Number value = 0;
1✔
614
                    if (node.readAttribute(attr).getValue().isNull()) {
1✔
615
                      internalLogger.warn("node {} has a Null variant.", node);
×
616
                    } else {
617
                      value = (Number) node.readAttribute(attr).getValue().getValue();
1✔
618
                    }
619

620
                    tdef.addColumn(p.getQualifiedName(), DataType.PARAMETER_VALUE);
1✔
621
                    cols.add(getPV(p, Instant.now().toEpochMilli(), value.intValue()));
1✔
622
                  }
623
                  break;
1✔
624
                case SINT64:
625
                  {
626
                    Number value = 0;
1✔
627
                    if (node.readAttribute(attr).getValue().isNull()) {
1✔
628
                      internalLogger.warn("node {} has a Null variant.", node);
×
629
                    } else {
630
                      value = (Number) node.readAttribute(attr).getValue().getValue();
1✔
631
                    }
632

633
                    tdef.addColumn(p.getQualifiedName(), DataType.PARAMETER_VALUE);
1✔
634
                    cols.add(getPV(p, Instant.now().toEpochMilli(), value.longValue()));
1✔
635
                  }
636
                  break;
1✔
637
                case STRING:
638
                  {
639
                    String value = "";
1✔
640
                    if (node.readAttribute(attr).getValue().isNull()) {
1✔
641
                      value = "NULL";
1✔
642
                    } else {
643
                      value = node.readAttribute(attr).getValue().getValue().toString();
1✔
644
                    }
645

646
                    tdef.addColumn(p.getQualifiedName(), DataType.PARAMETER_VALUE);
1✔
647
                    cols.add(getPV(p, Instant.now().toEpochMilli(), value));
1✔
648
                  }
649
                  break;
1✔
650
                case UINT32:
651
                  {
652
                    Number value = 0;
1✔
653
                    if (node.readAttribute(attr).getValue().isNull()) {
1✔
654
                      internalLogger.warn("node {} has a Null variant.", node);
×
655
                    } else {
656
                      value = (Number) node.readAttribute(attr).getValue().getValue();
1✔
657
                    }
658

659
                    tdef.addColumn(p.getQualifiedName(), DataType.PARAMETER_VALUE);
1✔
660
                    cols.add(getPV(p, Instant.now().toEpochMilli(), value.longValue()));
1✔
661
                  }
662
                  break;
1✔
663
                case UINT64:
664
                  {
665
                    Number value = 0;
1✔
666
                    if (node.readAttribute(attr).getValue().isNull()) {
1✔
667
                      internalLogger.warn("node {} has a Null variant.", node);
×
668
                    } else {
669
                      value = (Number) node.readAttribute(attr).getValue().getValue();
1✔
670
                    }
671

672
                    tdef.addColumn(p.getQualifiedName(), DataType.PARAMETER_VALUE);
1✔
673
                    cols.add(getPV(p, Instant.now().toEpochMilli(), value.longValue()));
1✔
674
                  }
675
                  break;
1✔
676
                default:
677
                  break;
678
              }
679

680
              log.debug("Pushing {} to stream", p.toString());
1✔
681

682
              columnCount++;
1✔
683
            }
1✔
684
            break;
1✔
685
          default:
686
            break;
687
        }
688

689
      } catch (UaException e) {
×
690
        // TODO Auto-generated catch block
691
        internalLogger.warn(e.toString());
×
692
        continue;
×
693
      }
1✔
694
    }
1✔
695

696
    pushTuple(tdef, cols);
1✔
697
    inCount.getAndAdd(columnCount);
1✔
698
  }
1✔
699

700
  private synchronized void pushTuple(TupleDefinition tdef, List<Object> cols) {
701
    Tuple t;
702
    t = new Tuple(tdef, cols);
1✔
703
    opcuaStream.emitTuple(t);
1✔
704
  }
1✔
705

706
  private static ParameterType getOrCreateType(
707
      XtceDb mdb, String name, Supplier<ParameterType.Builder<?>> supplier) {
708

709
    String fqn = XtceDb.YAMCS_SPACESYSTEM_NAME + NameDescription.PATH_SEPARATOR + name;
1✔
710
    ParameterType ptype = mdb.getParameterType(fqn);
1✔
711
    if (ptype != null) {
1✔
712
      return ptype;
1✔
713
    }
714
    ParameterType.Builder<?> typeb = supplier.get().setName(name);
1✔
715

716
    ptype = typeb.build();
1✔
717
    ((NameDescription) ptype).setQualifiedName(fqn);
1✔
718

719
    return mdb.addSystemParameterType(ptype);
1✔
720
  }
721

722
  public static ParameterType getBasicType(XtceDb mdb, Type type) {
723
    ParameterType pType = null;
1✔
724
    switch (type) {
1✔
725
      case BOOLEAN:
726
        return getOrCreateType(mdb, "boolean", () -> new BooleanParameterType.Builder());
1✔
727
      case STRING:
728
        return getOrCreateType(mdb, "string", () -> new StringParameterType.Builder());
1✔
729

730
      case FLOAT:
731
        return getOrCreateType(
1✔
732
            mdb, "float32", () -> new FloatParameterType.Builder().setSizeInBits(32));
1✔
733
      case DOUBLE:
734
        return getOrCreateType(
1✔
735
            mdb, "float64", () -> new FloatParameterType.Builder().setSizeInBits(64));
1✔
736
      case SINT32:
737
        return getOrCreateType(
1✔
738
            mdb,
739
            "sint32",
740
            () -> new IntegerParameterType.Builder().setSizeInBits(32).setSigned(true));
×
741
      case SINT64:
742
        return getOrCreateType(
1✔
743
            mdb,
744
            "sint64",
745
            () -> new IntegerParameterType.Builder().setSizeInBits(64).setSigned(true));
1✔
746
      case UINT32:
747
        return getOrCreateType(
1✔
748
            mdb,
749
            "uint32",
750
            () -> new IntegerParameterType.Builder().setSizeInBits(32).setSigned(false));
×
751
      case UINT64:
752
        return getOrCreateType(
1✔
753
            mdb,
754
            "uint64",
755
            () -> new IntegerParameterType.Builder().setSizeInBits(64).setSigned(false));
×
756
      default:
757
        break;
758
    }
759

760
    return pType;
×
761
  }
762

763
  public static ParameterValue getNewPv(Parameter parameter, long time) {
764
    ParameterValue pv = new ParameterValue(parameter);
1✔
765
    pv.setAcquisitionTime(time);
1✔
766
    pv.setGenerationTime(time);
1✔
767
    return pv;
1✔
768
  }
769

770
  public static ParameterValue getPV(Parameter parameter, long time, String v) {
771
    ParameterValue pv = getNewPv(parameter, time);
1✔
772
    pv.setEngValue(ValueUtility.getStringValue(v));
1✔
773
    return pv;
1✔
774
  }
775

776
  public static ParameterValue getPV(Parameter parameter, long time, double v) {
777
    ParameterValue pv = getNewPv(parameter, time);
1✔
778
    pv.setEngValue(ValueUtility.getDoubleValue(v));
1✔
779
    return pv;
1✔
780
  }
781

782
  public static ParameterValue getPV(Parameter parameter, long time, float v) {
783
    ParameterValue pv = getNewPv(parameter, time);
1✔
784
    pv.setEngValue(ValueUtility.getFloatValue(v));
1✔
785
    return pv;
1✔
786
  }
787

788
  public static ParameterValue getPV(Parameter parameter, long time, boolean v) {
789
    ParameterValue pv = getNewPv(parameter, time);
1✔
790
    pv.setEngValue(ValueUtility.getBooleanValue(v));
1✔
791
    return pv;
1✔
792
  }
793

794
  public static ParameterValue getPV(Parameter parameter, long time, long v) {
795
    ParameterValue pv = getNewPv(parameter, time);
1✔
796
    pv.setEngValue(ValueUtility.getSint64Value(v));
1✔
797
    return pv;
1✔
798
  }
799

800
  @Override
801
  public Status getLinkStatus() {
802
    return linkStatus;
1✔
803
  }
804

805
  @Override
806
  public boolean isDisabled() {
807
    return linkStatus == Status.DISABLED;
1✔
808
  }
809

810
  @Override
811
  public long getDataInCount() {
812
    return inCount.get();
1✔
813
  }
814

815
  @Override
816
  public long getDataOutCount() {
817
    return 0;
1✔
818
  }
819

820
  @Override
821
  public void resetCounters() {
822
    inCount.set(0);
1✔
823
  }
1✔
824

825
  /**
826
   * Selects first non-secured endpoint from endpoints found at discover URL. At the moment secured
827
   * endpoints are not supported.
828
   *
829
   * @return
830
   * @throws Exception
831
   */
832
  private OpcUaClient configureClient() throws Exception {
833

834
    List<EndpointDescription> endpoints = DiscoveryClient.getEndpoints(discoverURL).get();
1✔
835

836
    // At the moment, we do not support certificates.
837
    EndpointDescription selectedEndpoint = null;
1✔
838
    for (var endpoint : endpoints) {
1✔
839
      switch (endpoint.getSecurityMode()) {
1✔
840
        case Invalid:
841
          internalLogger.warn("Endpoint mode {} is not supported.", endpoint.getSecurityMode());
×
842
          break;
×
843
        case None:
844
          selectedEndpoint = endpoint;
1✔
845
          break;
1✔
846
        case Sign:
847
          internalLogger.warn("Endpoint mode {} is not supported.", endpoint.getSecurityMode());
×
848
          break;
×
849
        case SignAndEncrypt:
850
          internalLogger.warn("Endpoint mode {} is not supported.", endpoint.getSecurityMode());
×
851
          break;
852
      }
853

854
      if (selectedEndpoint != null) {
1✔
855
        break;
1✔
856
      }
857
    }
×
858

859
    if (selectedEndpoint == null) {
1✔
860
      throw new Exception("No viable endpoint found from list:" + endpoints);
×
861
    }
862

863
    OpcUaClientConfig builder = OpcUaClientConfig.builder().setEndpoint(selectedEndpoint).build();
1✔
864

865
    return OpcUaClient.create(builder);
1✔
866
  }
867

868
  /**
869
   * Adds new PV with the name of node.
870
   *
871
   * @param client
872
   * @param node
873
   */
874
  private void addOPCUAPV(OpcUaClient client, UaNode node) {
875

876
    if (node.getBrowseName()
1✔
877
        .getName()
1✔
878
        .contains(Character.toString(NameDescription.PATH_SEPARATOR))) {
1✔
879
      internalLogger.info(
×
880
          "{} ignored since it contains a {} character",
881
          node.getBrowseName().getName(),
×
882
          Character.toString(NameDescription.PATH_SEPARATOR));
×
883

884
    } else {
885

886
      /**
887
       * NOTE:For now we'll just flatten all the attributes instead of using an aggregate type for
888
       * attributes
889
       */
890
      for (AttributeId attr : AttributeId.values()) {
1✔
891

892
        ParameterType ptype = OPCUAAttrTypeToParamType(attr, node);
1✔
893

894
        String opcuaTranslatedQName = translateNodeToParamQName(client, node, attr);
1✔
895
        Parameter p = VariableParam.getForFullyQualifiedName(opcuaTranslatedQName);
1✔
896

897
        p.setParameterType(ptype);
1✔
898

899
        if (mdb.getParameter(p.getQualifiedName()) == null) {
1✔
900
          log.debug("Adding OPCUA object as parameter to mdb:{}", p.getQualifiedName());
1✔
901
          mdb.addParameter(p, true);
1✔
902

903
          nodeIDToParamsMap.put(new NodeIDAttrPair(node.getNodeId(), attr), (VariableParam) p);
1✔
904
        }
905
      }
906
    }
907
  }
1✔
908

909
  /**
910
   * Map nodeID name to a qualified name that can be used for a YAMCS PV.
911
   *
912
   * @param client
913
   * @param node
914
   * @param attr
915
   * @return
916
   */
917
  private String translateNodeToParamQName(OpcUaClient client, UaNode node, AttributeId attr) {
918
    LocalizedText localizedDisplayName = null;
1✔
919
    try {
920

921
      localizedDisplayName =
1✔
922
          (LocalizedText) (node.readAttribute(AttributeId.DisplayName).getValue().getValue());
1✔
923
    } catch (UaException e) {
×
924
      // TODO Auto-generated catch block
925
      e.printStackTrace();
×
926
    }
1✔
927
    String opcuaTranslatedQName =
1✔
928
        qualifiedName(
1✔
929
            parametersNamespace
930
                + NameDescription.PATH_SEPARATOR
931
                + node.getNodeId().toParseableString().replace(";", "-")
1✔
932
                + NameDescription.PATH_SEPARATOR
933
                + localizedDisplayName.getText(),
1✔
934
            attr.toString());
1✔
935

936
    return opcuaTranslatedQName;
1✔
937
  }
938

939
  /**
940
   * Browse node at nodePath relative to browseRoot.
941
   *
942
   * @param indent
943
   * @param client
944
   * @param browseRoot
945
   * @param nodePath in the format of "0:Root,0:Objects,2:HelloWorld,2:MyObject,2:Bar"
946
   * @throws Exception
947
   */
948
  private void browsePath(String indent, OpcUaClient client, NodeId startingNode, String nodePath)
949
      throws Exception {
950
    internalLogger.info("Browsing at " + startingNode);
1✔
951
    ArrayList<String> rPathTokens = new ArrayList<String>();
1✔
952
    ArrayList<RelativePathElement> relaitivePathElements = new ArrayList<RelativePathElement>();
1✔
953

954
    for (var pathToken : nodePath.split(",")) {
1✔
955
      rPathTokens.add(nodePath);
1✔
956

957
      int namespaceIndex = 0;
1✔
958

959
      String namespaceName = "";
1✔
960

961
      namespaceIndex = Integer.parseInt(pathToken.split(":")[0]);
1✔
962

963
      namespaceName = pathToken.split(":")[1];
1✔
964

965
      relaitivePathElements.add(
1✔
966
          new RelativePathElement(
967
              Identifiers.HierarchicalReferences,
968
              false,
1✔
969
              true,
1✔
970
              new QualifiedName(namespaceIndex, namespaceName)));
971
    }
972

973
    ArrayList<BrowsePath> list = new ArrayList<BrowsePath>();
1✔
974

975
    RelativePathElement[] elements = new RelativePathElement[relaitivePathElements.size()];
1✔
976

977
    relaitivePathElements.toArray(elements);
1✔
978

979
    list.add(new BrowsePath(startingNode, new RelativePath(elements)));
1✔
980

981
    TranslateBrowsePathsToNodeIdsResponse response = null;
1✔
982
    try {
983
      response = client.translateBrowsePaths(list).get();
1✔
984
    } catch (InterruptedException e) {
×
985
      internalLogger.warn(e.toString());
×
986
    } catch (ExecutionException e) {
×
987
      internalLogger.warn(e.toString());
×
988
    }
1✔
989

990
    BrowsePathResult result = Arrays.asList(response.getResults()).get(0);
1✔
991
    StatusCode statusCode = result.getStatusCode();
1✔
992

993
    if (statusCode.isBad()) {
1✔
994
      log.warn("Bad status code:" + statusCode);
1✔
995
      org.yamcs.yarch.protobuf.Db.Event ev =
996
          Event.newBuilder()
1✔
997
              .setGenerationTime(YamcsServer.getTimeService(yamcsInstance).getMissionTime())
1✔
998
              .setGenerationTime(YamcsServer.getTimeService(yamcsInstance).getMissionTime())
1✔
999
              .setSource(this.linkName)
1✔
1000
              .setType(this.linkName)
1✔
1001
              .setMessage("Failed to find node:" + nodePath + ". Error code info:" + statusCode)
1✔
1002
              .setSeverity(EventSeverity.ERROR)
1✔
1003
              .build();
1✔
1004
      eventProducer.sendEvent(ev);
1✔
1005

1006
      throw new Exception("Bad status code:" + statusCode);
1✔
1007

1008
    } else if (statusCode.isUncertain()) {
1✔
1009
      log.warn("Uncertain status code:" + statusCode);
×
1010
      return;
×
1011
    }
1012

1013
    try {
1014
      UaNode node =
1✔
1015
          client
1016
              .getAddressSpace()
1✔
1017
              .getNode(
1✔
1018
                  result.getTargets()[0].getTargetId().toNodeId(client.getNamespaceTable()).get());
1✔
1019

1020
      addOPCUAPV(client, node);
1✔
1021
    } catch (UaException e) {
×
1022
      internalLogger.warn(e.toString());
×
1023
    }
1✔
1024
  }
1✔
1025

1026
  private void createOPCUASubscriptions() {
1027
    createDataChangeListener();
1✔
1028
    Set<NodeId> nodeSet = new HashSet<NodeId>();
1✔
1029
    /**
1030
     * FIXME:This is super inefficient... The reason we collect these nodeIDs in a set is because
1031
     * otherwise we will have redundant subscription(s) since there is more than 1 attribute per
1032
     * nodeID given how nodeIDToParamsMap is designed
1033
     */
1034
    for (NodeIDAttrPair pair : nodeIDToParamsMap.keySet()) {
1✔
1035
      nodeSet.add(pair.nodeID);
1✔
1036
    }
1✔
1037

1038
    ArrayList<NodeId> variableNodes = new ArrayList<NodeId>();
1✔
1039
    for (NodeId id : nodeSet) {
1✔
1040
      Variant nodeClass = null;
1✔
1041
      try {
1042
        UaNode node = client.getAddressSpace().getNode(id);
1✔
1043

1044
        nodeClass = node.readAttribute(AttributeId.NodeClass).getValue();
1✔
1045

1046
      } catch (UaException e) {
×
1047
        internalLogger.warn(e.toString());
×
1048
      }
1✔
1049
      if (nodeClass != null) {
1✔
1050
        //        try {
1051
        switch (NodeClass.from((int) nodeClass.getValue())) {
1✔
1052
            // As per the spec, the only thing we can subscribe to is Variables
1053
          case Variable:
1054
            variableNodes.add(id);
1✔
1055
            break;
1056
        }
1057
      }
1058
    }
1✔
1059

1060
    try {
1061
      List<ManagedDataItem> dataItems = opcuaSubscription.createDataItems(variableNodes);
1✔
1062
      for (var dataItem : dataItems) {
1✔
1063
        log.debug("Status code for dataItem:{}", dataItem.getStatusCode());
1✔
1064
        OPCUAActiveSubs.addAndGet(1);
1✔
1065
      }
1✔
1066
    } catch (UaException e) {
×
1067
      internalLogger.warn(e.toString());
×
1068
    }
1✔
1069
  }
1✔
1070

1071
  /**
1072
   * Connects to OPCUA server and activates query all action.
1073
   *
1074
   * @param client
1075
   * @throws Exception
1076
   */
1077
  public void connectToOPCUAServer(OpcUaClient client) throws Exception {
1078
    internalLogger.info("Connecting to OPCUA server...");
1✔
1079
    client.connect().get();
1✔
1080

1081
    addAction(startAction);
1✔
1082
    startAction.setEnabled(true);
1✔
1083
  }
1✔
1084

1085
  /**
1086
   * Browses the tree on the OPCUA server and maps them to YAMCS Parameters.
1087
   *
1088
   * @param client
1089
   * @throws Exception
1090
   */
1091
  private void browseOPCUATree(OpcUaClient client) throws Exception {
1092
    // start browsing at root folder
1093
    internalLogger.info("Browsing OPCUA...");
1✔
1094
    for (var p : relativeNodePaths) {
1✔
1095
      int namespaceIndex = (int) p.rootNodeID.get("namespaceIndex");
1✔
1096
      String identifier = (String) p.rootNodeID.get("identifier");
1✔
1097
      IdType identifierType = IdType.valueOf((String) p.rootNodeID.get("identifierType"));
1✔
1098

1099
      browsePath(
1✔
1100
          endpointURL, client, getNewNodeID(identifierType, namespaceIndex, identifier), p.path);
1✔
1101
    }
1✔
1102
  }
1✔
1103

1104
  /**
1105
   * Get new OPCUA-compliant NodeID object that is created from NamespaceIndex and Identifier. At
1106
   * the moment only String and Numeric node ids are supported.
1107
   *
1108
   * @param rootIdentifierType
1109
   * @param NamespaceIndex
1110
   * @param Identifier
1111
   * @return
1112
   */
1113
  private NodeId getNewNodeID(IdType rootIdentifierType, int NamespaceIndex, String Identifier) {
1114
    NodeId nodeID = null;
1✔
1115
    switch (rootIdentifierType) {
1✔
1116
      case Guid:
1117
        internalLogger.warn("Guid nodeID is not supported");
×
1118
        break;
×
1119
      case Numeric:
1120
        nodeID = new NodeId(NamespaceIndex, Integer.parseInt(Identifier));
1✔
1121
        break;
1✔
1122
      case Opaque:
1123
        internalLogger.warn("Guid Opaque is not supported");
×
1124
        break;
×
1125
      case String:
1126
        nodeID = new NodeId(NamespaceIndex, Identifier);
×
1127
        break;
1128
    }
1129
    return nodeID;
1✔
1130
  }
1131

1132
  /** Data listener for realtime OPCUA server updates. */
1133
  private void createDataChangeListener() {
1134
    try {
1135
      opcuaSubscription = ManagedSubscription.create(client, publishInterval);
1✔
1136
    } catch (UaException e) {
×
1137
      // TODO Auto-generated catch block
1138
      e.printStackTrace();
×
1139
    }
1✔
1140
    opcuaSubscription.addDataChangeListener(
1✔
1141
        (items, values) -> {
1142
          for (int i = 0; i < items.size(); i++) {
1✔
1143
            NodeIDAttrPair nodeAttrKey =
1✔
1144
                new NodeIDAttrPair(items.get(i).getNodeId(), AttributeId.Value);
1✔
1145
            log.debug(
1✔
1146
                "subscription value received: item={}, value={}",
1147
                items.get(i).getNodeId(),
1✔
1148
                values.get(i).getValue());
1✔
1149

1150
            log.debug(
1✔
1151
                "Pushing new PV for param name {} which is mapped to NodeID {}",
1152
                nodeIDToParamsMap.get(nodeAttrKey),
1✔
1153
                items.get(i).getNodeId());
1✔
1154

1155
            TupleDefinition tdef = gftdef.copy();
1✔
1156
            List<Object> cols = new ArrayList<>(4 + 1);
1✔
1157
            //            FIXME: Add leap seconds.... as config or get it from YAMCS API.
1158
            long gentime =
1✔
1159
                values
1160
                    .get(i)
1✔
1161
                    .getSourceTime()
1✔
1162
                    .getJavaInstant()
1✔
1163
                    .plus(37, ChronoUnit.SECONDS)
1✔
1164
                    .toEpochMilli();
1✔
1165
            cols.add(gentime);
1✔
1166
            cols.add(parametersNamespace);
1✔
1167
            cols.add(0);
1✔
1168
            cols.add(gentime);
1✔
1169

1170
            /**
1171
             * TODO:Not sure if this is the best way to do this since the aggregate values will be
1172
             * partially updated. Another potential approach might be to decouple the live OPCUA
1173
             * data(subscriptions) via namespaces. For example; have a "special" namespace called
1174
             * "subscriptions" that ONLY gets updated with items. And maybe another namespace for
1175
             * static data...maybe.
1176
             *
1177
             * <p>Another option is to flatten everything and have no aggregate types at all. That
1178
             * approach might even simplify the code quite a bit...
1179
             *
1180
             * <p>Another question worth answering before moving forward is to find out whether or
1181
             * not it is concrete in the OPCUA protocol what data can change in real time and which
1182
             * data is "static". Not sure if there is any "static" data given that clients have the
1183
             * ability of writing to values... might be worth a test.
1184
             */
1185
            log.debug(
1✔
1186
                "Data({}) chnage triggered for {}",
1187
                values.get(i).getValue(),
1✔
1188
                nodeIDToParamsMap.get(nodeAttrKey));
1✔
1189

1190
            if (nodeIDToParamsMap.get(nodeAttrKey) == null) {
1✔
1191
              log.debug("No parameter mapping found for {}", nodeAttrKey.nodeID);
×
1192
              continue;
×
1193
            } else {
1194
              log.debug(
1✔
1195
                  String.format(
1✔
1196
                      "parameter mapping found for {} and {}",
1197
                      nodeAttrKey.nodeID,
1198
                      nodeAttrKey.attrID));
1199
            }
1200

1201
            if (values.get(i).getValue() != null && values.get(i).getValue().getValue() != null) {
1✔
1202

1203
              switch (nodeIDToParamsMap.get(nodeAttrKey).getParameterType().getValueType()) {
1✔
1204
                case BOOLEAN:
1205
                  {
1206
                    boolean value = (boolean) values.get(i).getValue().getValue();
1✔
1207

1208
                    tdef.addColumn(
1✔
1209
                        nodeIDToParamsMap.get(nodeAttrKey).getQualifiedName(),
1✔
1210
                        DataType.PARAMETER_VALUE);
1211
                    cols.add(getPV(nodeIDToParamsMap.get(nodeAttrKey), gentime, value));
1✔
1212
                  }
1213
                  break;
1✔
1214
                case DOUBLE:
1215
                  {
1216
                    Number value = (Number) values.get(i).getValue().getValue();
1✔
1217

1218
                    tdef.addColumn(
1✔
1219
                        nodeIDToParamsMap.get(nodeAttrKey).getQualifiedName(),
1✔
1220
                        DataType.PARAMETER_VALUE);
1221
                    cols.add(
1✔
1222
                        getPV(nodeIDToParamsMap.get(nodeAttrKey), gentime, value.doubleValue()));
1✔
1223
                  }
1224
                  break;
1✔
1225
                case FLOAT:
1226
                  {
1227
                    Number value = (Number) values.get(i).getValue().getValue();
1✔
1228

1229
                    tdef.addColumn(
1✔
1230
                        nodeIDToParamsMap.get(nodeAttrKey).getQualifiedName(),
1✔
1231
                        DataType.PARAMETER_VALUE);
1232
                    cols.add(
1✔
1233
                        getPV(nodeIDToParamsMap.get(nodeAttrKey), gentime, value.floatValue()));
1✔
1234
                  }
1235
                  break;
1✔
1236
                case SINT32:
1237
                  {
1238
                    Number value = (Number) values.get(i).getValue().getValue();
1✔
1239
                    tdef.addColumn(
1✔
1240
                        nodeIDToParamsMap.get(nodeAttrKey).getQualifiedName(),
1✔
1241
                        DataType.PARAMETER_VALUE);
1242
                    cols.add(getPV(nodeIDToParamsMap.get(nodeAttrKey), gentime, value.intValue()));
1✔
1243
                  }
1244
                  break;
1✔
1245
                case SINT64:
1246
                  {
1247
                    Number value = (Number) values.get(i).getValue().getValue();
1✔
1248

1249
                    tdef.addColumn(
1✔
1250
                        nodeIDToParamsMap.get(nodeAttrKey).getQualifiedName(),
1✔
1251
                        DataType.PARAMETER_VALUE);
1252
                    cols.add(getPV(nodeIDToParamsMap.get(nodeAttrKey), gentime, value.longValue()));
1✔
1253
                  }
1254
                  break;
1✔
1255
                case STRING:
1256
                  {
1257
                    String value = (String) values.get(i).getValue().getValue().toString();
1✔
1258

1259
                    tdef.addColumn(
1✔
1260
                        nodeIDToParamsMap.get(nodeAttrKey).getQualifiedName(),
1✔
1261
                        DataType.PARAMETER_VALUE);
1262
                    cols.add(getPV(nodeIDToParamsMap.get(nodeAttrKey), gentime, value));
1✔
1263
                  }
1264
                  break;
1✔
1265
                case UINT32:
1266
                  {
1267
                    Number value = (Number) values.get(i).getValue().getValue();
1✔
1268
                    tdef.addColumn(
1✔
1269
                        nodeIDToParamsMap.get(nodeAttrKey).getQualifiedName(),
1✔
1270
                        DataType.PARAMETER_VALUE);
1271
                    cols.add(getPV(nodeIDToParamsMap.get(nodeAttrKey), gentime, value.longValue()));
1✔
1272
                  }
1273
                  break;
1✔
1274
                case UINT64:
1275
                  {
1276
                    Number value = (Number) values.get(i).getValue().getValue();
1✔
1277

1278
                    tdef.addColumn(
1✔
1279
                        nodeIDToParamsMap.get(nodeAttrKey).getQualifiedName(),
1✔
1280
                        DataType.PARAMETER_VALUE);
1281
                    cols.add(getPV(nodeIDToParamsMap.get(nodeAttrKey), gentime, value.longValue()));
1✔
1282
                  }
1283
                  break;
1✔
1284
                default:
1285
                  break;
1286
              }
1287

1288
              pushTuple(tdef, cols);
1✔
1289

1290
              inCount.getAndAdd(1);
1✔
1291
            } else {
1292
              // TODO:Add some type emptyValue count for OPS.
1293
              log.warn(
×
1294
                  "Data chnage triggered for {}, but it empty. This should not happen.",
1295
                  nodeIDToParamsMap.get(nodeAttrKey).getQualifiedName());
×
1296
            }
1297
          }
1298
        });
1✔
1299
  }
1✔
1300

1301
  /**
1302
   * Get new ParameterType for the specified attribute of the node. Particularly useful for Value
1303
   * attributes of nodes.
1304
   *
1305
   * @param attr
1306
   * @param node
1307
   * @return
1308
   */
1309
  private ParameterType OPCUAAttrTypeToParamType(AttributeId attr, UaNode node) {
1310
    ParameterType pType = null;
1✔
1311

1312
    switch (attr) {
1✔
1313
      case AccessLevel:
1314
        pType = getBasicType(mdb, Type.STRING);
1✔
1315
        break;
1✔
1316
      case ArrayDimensions:
1317
        pType = getBasicType(mdb, Type.STRING);
1✔
1318
        break;
1✔
1319
      case BrowseName:
1320
        pType = getBasicType(mdb, Type.STRING);
1✔
1321
        break;
1✔
1322
      case ContainsNoLoops:
1323
        pType = getBasicType(mdb, Type.STRING);
1✔
1324
        break;
1✔
1325
      case DataType:
1326
        pType = getBasicType(mdb, Type.STRING);
1✔
1327
        break;
1✔
1328
      case Description:
1329
        pType = getBasicType(mdb, Type.STRING);
1✔
1330
        break;
1✔
1331
      case DisplayName:
1332
        pType = getBasicType(mdb, Type.STRING);
1✔
1333
        break;
1✔
1334
      case EventNotifier:
1335
        pType = getBasicType(mdb, Type.STRING);
1✔
1336
        break;
1✔
1337
      case Executable:
1338
        pType = getBasicType(mdb, Type.STRING);
1✔
1339
        break;
1✔
1340
      case Historizing:
1341
        pType = getBasicType(mdb, Type.STRING);
1✔
1342
        break;
1✔
1343
      case InverseName:
1344
        pType = getBasicType(mdb, Type.STRING);
1✔
1345
        break;
1✔
1346
      case IsAbstract:
1347
        pType = getBasicType(mdb, Type.STRING);
1✔
1348
        break;
1✔
1349
      case MinimumSamplingInterval:
1350
        pType = getBasicType(mdb, Type.STRING);
1✔
1351
        break;
1✔
1352
      case NodeClass:
1353
        pType = getBasicType(mdb, Type.STRING);
1✔
1354
        break;
1✔
1355
      case NodeId:
1356
        pType = getBasicType(mdb, Type.STRING);
1✔
1357
        break;
1✔
1358
      case Symmetric:
1359
        pType = getBasicType(mdb, Type.STRING);
1✔
1360
        break;
1✔
1361
      case UserAccessLevel:
1362
        pType = getBasicType(mdb, Type.STRING);
1✔
1363
        break;
1✔
1364
      case UserExecutable:
1365
        pType = getBasicType(mdb, Type.STRING);
1✔
1366
        break;
1✔
1367
      case UserWriteMask:
1368
        pType = getBasicType(mdb, Type.STRING);
1✔
1369
        break;
1✔
1370
      case Value:
1371
        try {
1372

1373
          var value = node.readAttribute(attr).getValue();
1✔
1374

1375
          if (value.isNotNull()) {
1✔
1376
            NodeId valueObjectType =
1✔
1377
                value.getDataType().get().toNodeId(client.getNamespaceTable()).get();
1✔
1378

1379
            /** As per the spec:https://reference.opcfoundation.org/Core/Part6/v104/docs/5.1.2 */
1380
            if (valueObjectType.equals(Identifiers.SByte)) {
1✔
1381
              pType = getBasicType(mdb, Type.SINT32);
×
1382
            } else if (valueObjectType.equals(Identifiers.Byte)) {
1✔
1383
              pType = getBasicType(mdb, Type.SINT32);
×
1384
            } else if (valueObjectType.equals(Identifiers.Int16)) {
1✔
1385
              pType = getBasicType(mdb, Type.SINT32);
×
1386
            } else if (valueObjectType.equals(Identifiers.UInt16)) {
1✔
1387
              pType = getBasicType(mdb, Type.SINT32);
×
1388
            } else if (valueObjectType.equals(Identifiers.Int32)) {
1✔
1389
              pType = getBasicType(mdb, Type.SINT32);
1✔
1390
            } else if (valueObjectType.equals(Identifiers.UInt32)) {
1✔
1391
              pType = getBasicType(mdb, Type.UINT32);
1✔
1392
            } else if (valueObjectType.equals(Identifiers.Int64)) {
1✔
1393
              pType = getBasicType(mdb, Type.SINT64);
1✔
1394
            } else if (valueObjectType.equals(Identifiers.UInt64)) {
1✔
1395
              pType = getBasicType(mdb, Type.UINT64);
1✔
1396
            } else if (valueObjectType.equals(Identifiers.Float)) {
1✔
1397
              pType = getBasicType(mdb, Type.FLOAT);
1✔
1398
            } else if (valueObjectType.equals(Identifiers.Double)) {
1✔
1399
              pType = getBasicType(mdb, Type.DOUBLE);
1✔
1400
            } else if (valueObjectType.equals(Identifiers.String)) {
1✔
1401
              pType = getBasicType(mdb, Type.STRING);
1✔
1402
            } else if (valueObjectType.equals(Identifiers.Boolean)) {
1✔
1403
              pType = getBasicType(mdb, Type.BOOLEAN);
1✔
1404
            }
1405
          } else {
1✔
1406
            pType = getBasicType(mdb, Type.STRING);
×
1407
          }
1408

1409
        } catch (UaException e) {
×
1410
          internalLogger.warn(e.toString());
×
1411
        }
1✔
1412
        break;
×
1413
      case ValueRank:
1414
        pType = getBasicType(mdb, Type.STRING);
1✔
1415
        break;
1✔
1416
      case WriteMask:
1417
        pType = getBasicType(mdb, Type.STRING);
1✔
1418
        break;
1✔
1419
      default:
1420
        break;
1421
    }
1422

1423
    return pType;
1✔
1424
  }
1425

1426
  /**
1427
   * Subscribe to OPCUA events as per the
1428
   * spec:https://reference.opcfoundation.org/Core/Part5/v104/docs/6.4.2
1429
   *
1430
   * @param client
1431
   * @throws InterruptedException
1432
   * @throws ExecutionException
1433
   */
1434
  private void subscribeToEvents(OpcUaClient client)
1435
      throws InterruptedException, ExecutionException {
1436
    // create a subscription and a monitored item
1437
    UaSubscription subscription = client.getSubscriptionManager().createSubscription(1000.0).get();
1✔
1438

1439
    ReadValueId readValueId =
1✔
1440
        new ReadValueId(
1441
            Identifiers.Server, AttributeId.EventNotifier.uid(), null, QualifiedName.NULL_VALUE);
1✔
1442

1443
    // client handle must be unique per item
1444
    UInteger clientHandle = uint(clientHandles.getAndIncrement());
1✔
1445

1446
    EventFilter eventFilter =
1✔
1447
        new EventFilter(
1448
            new SimpleAttributeOperand[] {
1449
              new SimpleAttributeOperand(
1450
                  Identifiers.BaseEventType,
1451
                  new QualifiedName[] {new QualifiedName(0, "EventId")},
1452
                  AttributeId.Value.uid(),
1✔
1453
                  null),
1454
              new SimpleAttributeOperand(
1455
                  Identifiers.BaseEventType,
1456
                  new QualifiedName[] {new QualifiedName(0, "EventType")},
1457
                  AttributeId.Value.uid(),
1✔
1458
                  null),
1459
              new SimpleAttributeOperand(
1460
                  Identifiers.BaseEventType,
1461
                  new QualifiedName[] {new QualifiedName(0, "Severity")},
1462
                  AttributeId.Value.uid(),
1✔
1463
                  null),
1464
              new SimpleAttributeOperand(
1465
                  Identifiers.BaseEventType,
1466
                  new QualifiedName[] {new QualifiedName(0, "Time")},
1467
                  AttributeId.Value.uid(),
1✔
1468
                  null),
1469
              new SimpleAttributeOperand(
1470
                  Identifiers.BaseEventType,
1471
                  new QualifiedName[] {new QualifiedName(0, "Message")},
1472
                  AttributeId.Value.uid(),
1✔
1473
                  null)
1474
            },
1475
            new ContentFilter(null));
1476

1477
    MonitoringParameters parameters =
1✔
1478
        new MonitoringParameters(
1479
            clientHandle,
1480
            0.0,
1✔
1481
            ExtensionObject.encode(client.getStaticSerializationContext(), eventFilter),
1✔
1482
            uint(10),
1✔
1483
            true);
1✔
1484

1485
    MonitoredItemCreateRequest request =
1✔
1486
        new MonitoredItemCreateRequest(readValueId, MonitoringMode.Reporting, parameters);
1487

1488
    List<UaMonitoredItem> items =
1✔
1489
        subscription.createMonitoredItems(TimestampsToReturn.Both, newArrayList(request)).get();
1✔
1490

1491
    // do something with the value updates
1492
    UaMonitoredItem monitoredItem = items.get(0);
1✔
1493

1494
    monitoredItem.setEventConsumer(
1✔
1495
        (item, vs) -> {
1496
          internalLogger.info("Event Received from {}", item.getReadValueId().getNodeId());
1✔
1497

1498
          StringBuilder eventText = new StringBuilder();
1✔
1499

1500
          ByteString eventId;
1501
          NodeId eventType;
1502
          UShort eventSeverity;
1503
          DateTime eventTime;
1504
          LocalizedText eventMessage;
1505

1506
          for (int i = 0; i < vs.length; i++) {
1✔
1507
            internalLogger.info("\tvariant[{}]: {}", i, vs[i].getValue());
1✔
1508
          }
1509

1510
          eventId = (ByteString) vs[0].getValue();
1✔
1511
          eventType = (NodeId) vs[1].getValue();
1✔
1512
          eventSeverity = (UShort) vs[2].getValue();
1✔
1513
          eventTime = (DateTime) vs[3].getValue();
1✔
1514
          eventMessage = (LocalizedText) vs[4].getValue();
1✔
1515

1516
          //          FIXME:Map these values to YAMCS API
1517
          eventText.append("eventId:" + eventId);
1✔
1518
          eventText.append("\n");
1✔
1519
          eventText.append("eventType:" + eventType);
1✔
1520
          eventText.append("\n");
1✔
1521
          eventText.append("eventSeverity:" + eventSeverity);
1✔
1522
          eventText.append("\n");
1✔
1523
          eventText.append("eventTime:" + eventTime);
1✔
1524
          eventText.append("\n");
1✔
1525
          eventText.append("eventMessage:" + eventMessage);
1✔
1526
          org.yamcs.yarch.protobuf.Db.Event ev =
1527
              Event.newBuilder()
1✔
1528
                  .setGenerationTime(YamcsServer.getTimeService(yamcsInstance).getMissionTime())
1✔
1529
                  .setGenerationTime(YamcsServer.getTimeService(yamcsInstance).getMissionTime())
1✔
1530
                  .setSource(this.linkName)
1✔
1531
                  .setType(this.linkName)
1✔
1532
                  .setMessage(eventText.toString())
1✔
1533
                  .setSeverity(EventSeverity.INFO)
1✔
1534
                  .build();
1✔
1535
          eventProducer.sendEvent(ev);
1✔
1536
        });
1✔
1537
  }
1✔
1538

1539
  @Override
1540
  public void setupSystemParameters(SystemParametersService sysParamService) {
1541
    super.setupSystemParameters(sysParamService);
1✔
1542
    OPCUAStatusParam =
1✔
1543
        sysParamService.createEnumeratedSystemParameter(
1✔
1544
            linkName + "/OPCUAStatusParam",
1545
            OPCUAINITStatus.class,
1546
            "The current status of OPCUA client");
1547
    EnumeratedParameterType spLinkStatusType =
1✔
1548
        (EnumeratedParameterType) OPCUAStatusParam.getParameterType();
1✔
1549
    spLinkStatusType
1✔
1550
        .enumValue(OPCUAINITStatus.OPCUA_INIT_CONFIG.name())
1✔
1551
        .setDescription(
1✔
1552
            "This link is in the configuration stage(Configuring OPCUA parameters such as certificates)");
1553
    spLinkStatusType
1✔
1554
        .enumValue(OPCUAINITStatus.OPCUA_INIT_TREE.name())
1✔
1555
        .setDescription(
1✔
1556
            "The link is parsing the OPCUA Tree and mapping them to PVs."
1557
                + " Depending on configuration, this can take a while.");
1558

1559
    spLinkStatusType
1✔
1560
        .enumValue(OPCUAINITStatus.OPCUA_INIT_TREE_FAILED.name())
1✔
1561
        .setDescription("The initial parsing of configured nodes failed.");
1✔
1562
    spLinkStatusType
1✔
1563
        .enumValue(OPCUAINITStatus.OPCUA_INIT_EVENTS.name())
1✔
1564
        .setDescription("The link is configuring and subscribing to OPCUA events");
1✔
1565
    spLinkStatusType
1✔
1566
        .enumValue(OPCUAINITStatus.OPCUA_INIT_DATA_SUBSCRIPTION.name())
1✔
1567
        .setDescription(
1✔
1568
            "The link is creating subscriptions for each node that was parsed from the tree"
1569
                + "that has a Value attribute.");
1570
    spLinkStatusType
1✔
1571
        .enumValue(OPCUAINITStatus.OPCUA_INIT_ALL_DATA_QUERY.name())
1✔
1572
        .setDescription(
1✔
1573
            "The link is querying all attributes of all parsed nodes."
1574
                + "This is can be configured to be done at startup.");
1575
    spLinkStatusType
1✔
1576
        .enumValue(OPCUAINITStatus.OPCUA_INIT_OK.name())
1✔
1577
        .setDescription(
1✔
1578
            "The link is done with all OPCUA initialization. It is in an usable state.");
1579

1580
    OPCUAActiveSubsParam =
1✔
1581
        sysParamService.createSystemParameter(
1✔
1582
            linkName + "/OPCUAActiveSubs",
1583
            Type.UINT64,
1584
            "The total number of active opcua subscriptions");
1585
  }
1✔
1586

1587
  @Override
1588
  public List<ParameterValue> getSystemParameters() {
1589
    long time = getCurrentTime();
1✔
1590
    ArrayList<ParameterValue> list = new ArrayList<>();
1✔
1591

1592
    list.add(
1✔
1593
        org.yamcs.parameter.SystemParametersService.getPV(
1✔
1594
            OPCUAStatusParam, time, currentOPCUAStatus));
1595
    list.add(
1✔
1596
        org.yamcs.parameter.SystemParametersService.getPV(
1✔
1597
            OPCUAActiveSubsParam, time, OPCUAActiveSubs.get()));
1✔
1598
    try {
1599
      super.collectSystemParameters(time, list);
1✔
1600
    } catch (Exception e) {
×
1601
      log.error("Exception caught when collecting link system parameters", e);
×
1602
    }
1✔
1603
    return list;
1✔
1604
  }
1605
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc