OPCUA Test Orchestration

Hello,

Is it possible to have a few examples on how to use the Test Orchestrator, specifically for OPC-UA?
I was looking for a simple example on how to create a test for an event (e.g., a tag changes it’s value and something needs to be triggered on IoT side) and then for a command (e.g., sending order data).

I’ve personally not been using the Test Solution for a quite a while now so I’m in the process of refreshing some lost knowledge and, currently, my Test Solution is completely empty, so straight out of the Scaffolding process.

Thank you! :folded_hands:

Hi @Rui_Frontwell ,

In OPCUA - Critical Manufacturing Developer Portal you have already, some information. The tests depend a lot on your context and the type of testing that you are doing. We support tests that mock the MES and tests against a system. All of this is configured through plugins in the scenario configuration.

We have an example using REST Server at mes-common-library/features/IoTMTConnect/IoTMTConnect.Tests/IoTMTConnect.Tests.IoT/Tests/MTConnect.cs at 11.3/dev · criticalmanufacturing/mes-common-library

        [TestInitialize]
        public void Initialize()
        {
            PORT = new Random().Next(5000, 30000);
            MASTERDATA = Path.Combine(Path.GetTempPath(), $"{TestContext.TestName}-{Guid.NewGuid():N}.json");
            File.WriteAllText(MASTERDATA, File.ReadAllText(MASTERDATA_TEMPLATE).Replace("__DEFAULTPORT__", PORT.ToString()));

            Configuration = new ScenarioConfiguration()
             //Configure IoT Manager
             .ManagerId("MTConnectManager")
             .WriteLogsTo(Path.Combine(Path.GetTempPath(), $"{TestContext.TestName}-{Guid.NewGuid():N}-logs.txt"))
             .Config(new Common.Objects.Config.ConfigBuilder()
                 .CacheLocation(Path.GetTempPath())
                 .Build())
              // Settings for starting IoT manager
              .StartMode<LocalStartMode.PluginMain>(new LocalStartMode.Plugin.SettingsBuilder()
                  .ManagerLocation(Path.Join(PACKAGES_LOCATION, MANAGER))
                  .UseOtlpLogging(false)
                  .Build())
             // Configure MES Mock System 
             .SystemPlugin<MockSystem.PluginMain>(new MockSystem.Plugin.SettingsBuilder()
                 .Repository(PACKAGES_LOCATION)
                 //  .Port(49202)
                 .MasterdataPath(MASTERDATA)
                 .AddSite("TestSite")
                 .AddManager("MTConnectManager")
                 .AddControllerInstance("Demo MTConnect Controller [A.1]", "MTConnectManager", "TestSite")
                 .AddDriverInstance("Demo MTConnect Controller [A.1]", "MTConnect", "MTConnectManager", "TestSite")
                 .Build())
             // Configure the equipment simulator
             .AddSimulatorPlugin<RestServer.PluginMain>(new RestServer.Plugin.SettingsBuilder()
                 .Address("http://0.0.0.0", PORT)
                 .Build());
        }

Note that the difference to your use case is the configuration of the Simulator Plugin.

The driver OPC-UA buy using the DriverInstanceAlias (e.g .DriverInstanceAlias(“OPCUA”)), replicates the tags you have configured in your system and will automatically host them in an OPC-UA server. I believe this is currently only working for the scenario where your test runs against the MES.

            var opcuaBuilder = new IoTTestOrchestrator.OPCUA.Plugin.SettingsBuilder()
                .Address(opcuaAddress)
                .DriverInstanceAlias("OPCUA");

You can also declare them one by one or through a json file.

         var opcuaBuilder = new IoTTestOrchestrator.OPCUA.Plugin.SettingsBuilder()
                .Address(opcuaAddress)
                .AddTag(new OpcTag()
        {
            Name = $"Humidity",
            NodeId = $"ns=2;s=Humidity",
            AccessMode = AccessMode.ReadAndWrite,
            Value = JsonSerializer.SerializeToElement(45.5),
            Type = "Float"
        }, "CNC0001")
                .DriverInstanceAlias("OPCUA");
            var opcuaBuilder = new IoTTestOrchestrator.OPCUA.Plugin.SettingsBuilder()
                .Address(opcuaAddress)
                .AddTagsFromJSON(File.ReadAllText(Path.Combine(assetDirectory, "JsonTags", "tags.json")))
                .DriverInstanceAlias("OPCUA");

Example json:

{
    "NodeTree": [
        {
            "NodeBranch": "CNC0001",
            "Nodes": [
                {
                    "Name": "ns=2;s=Temperature",
                    "Id": "Temperature",
                    "Type": "String",
                    "Value": "100",
                    "AccessMode": "ReadAndWrite"
                },
                {
                    "Name": "ns=2;s=QualiVision.MESAdapter.JobsStatus.JobsStatus",
                    "Id": "JobStatus",
                    "Type": "Custom",
                    "CustomDataType": "QualiVision.opcuabb.Job",
                    "Value": {},
                    "AccessMode": "ReadAndWrite"
                },
                {
                    "Name": "ns=2;s=QualiVision.MESAdapter.ShiftViewStatus.ShiftViewStatus",
                    "Id": "ShiftViewStatus",
                    "Type": "Custom",
                    "CustomDataType": "QualiVision.opcuabb.TimeBoxData",
                    "Value": {},
                    "AccessMode": "ReadAndWrite"
                },
                {
                    "Name": "ns=2;s=TestCustomProperty",
                    "Id": "TestCustomProperty",
                    "Type": "String",
                    "Value": "",
                    "AccessMode": "ReadAndWrite"
                },
                {
                    "Name": "ns=2;s=CodeCustomProperty",
                    "Id": "CodeCustomProperty",
                    "Type": "Double",
                    "Value": 0,
                    "AccessMode": "ReadAndWrite"
                },
                {
                    "Name": "ns=3;s=namespace_three_string_address",
                    "Id": "namespace_three_string_address",
                    "Type": "String",
                    "Value": "100",
                    "AccessMode": "ReadAndWrite"
                },
                {
                    "Name": "ns=3;i=101",
                    "Id": "namespace_three_numeric_address",
                    "Type": "String",
                    "Value": "100",
                    "AccessMode": "ReadAndWrite"
                },
                {
                    "Name": "ns=3;s=AirConditioner_9.Humidity",
                    "Id": "HumidityCT",
                    "Type": "Double",
                    "Value": 53,
                    "AccessMode": "ReadAndWrite"
                },
                {
                    "Name": "ns=3;s=AirConditioner_1.PowerConsumption",
                    "Id": "PowerConsumptionCT",
                    "Type": "Double",
                    "Value": 122,
                    "AccessMode": "ReadAndWrite"
                }
            ]
        }
    ]
}

There are other configurations like commands, file server and server side events:

            var opcuaBuilder = new IoTTestOrchestrator.OPCUA.Plugin.SettingsBuilder()
                .Address(opcuaAddress)
                .AddNamespace("urn:yourcompany:default:v1")
                .AddNamespace("urn:yourcompany:machines:v1")
                // Register real OPC UA custom methods ahead of server start
               .AddCustomCommand(new IoTTestOrchestrator.OPCUA.Plugin.CustomCommandBuilder("fbiGetData", "ns=2;s=prgMES.fbiGetData#Methode", "ns=2;s=prgMES.fbiGetData")
                    .Output("Result", "String")
                    .Build())
                .AddCustomCommand(new IoTTestOrchestrator.OPCUA.Plugin.CustomCommandBuilder("fbiPrepareEquipment", "ns=2;s=prgMES.fbiPrepareEquipment#Methode", "ns=2;s=prgMES.fbiPrepareEquipment")
                    .Input("Command", "UInt16")
                    .Build())
                .AddCustomCommand(new IoTTestOrchestrator.OPCUA.Plugin.CustomCommandBuilder("StartMachine", "ns=2;s=Machines/Machine_1/StartMachine", "ns=2;s=Machines/Machine_1")
                    .Build())
                .AddCustomDataTypesFromJson(JobStatusCustomDataTypesJson)
                .AddTagsFromJSON(File.ReadAllText(Path.Combine(assetDirectory, "JsonTags", "tags.json")))
                .AddCustomEvent(Path.Combine(assetDirectory, "CustomTemplates", "CustomEvent.json"))
                .AddCustomEvent(Path.Combine(assetDirectory, "CustomTemplates", "CustomTemplateEventPropExtendedData.json"))
                .FileServer(Path.Combine(assetDirectory, "TestFileServer"))
                .DriverInstanceAlias("OPCUA");

For the test itself,

[TestMethod]
        public void OPCUAReadAndWriteTagTemperature()
        {
            #region Setup

            var controllerInstance = testContext.Instances["Controller"] as IControllerInstanceContext;
            var controllerInstanceContext = controllerInstance as IInstanceContext;
            var driverInstanceLog = (testContext.Instances["OPCUA"] as IInstanceContext).Log;

            #endregion Setup

            // Utility to make sure that the event was created and subscribed
            testScenario.Utilities.WaitFor(30, "TemperatureChanged subscription heartbeat was not received", () =>
            {
                return driverInstanceLog.Any(log =>
                    log.Contains("Subscription Heartbeat for event 'TemperatureChanged'", StringComparison.OrdinalIgnoreCase));
            });

            var expectedTemperature = Random.Shared.Next(200, 1000).ToString();

            // Set a tag value in the simulator
            opcuaSimulator.WriteTag("Temperature", expectedTemperature);
            // Check temperature was writter
            Assert.AreEqual(expectedTemperature, opcuaSimulator.ReadTag("Temperature")?.ToString());

            controllerInstanceContext.Log.Clear();

            using var replyReceived = new ManualResetEventSlim(false);
            string replyValue = string.Empty;
            Exception replyHandlerError = null;

            // Calls via messagebus a system event listener to trigger a tag read and waits for the reply and validates it
            controllerInstance.SystemEvent("Cmf.Test.OPCUA.ReadTag.Temperature", "This should trigger a GetEquipmentValue and receive back the value read", IoTTestOrchestrator.Common.Objects.WebSockets.SendType.SendRequest, (message) =>
            {
                try
                {
                    var content = JObject.Parse(message);
                    replyValue = content["reply"]?.ToString() ?? string.Empty;

                    if (string.IsNullOrWhiteSpace(replyValue))
                    {
                        replyHandlerError = new InvalidOperationException($"Reply payload did not contain 'reply': {message}");
                    }
                }
                catch (Exception ex)
                {
                    replyHandlerError = ex;
                }
                finally
                {
                    replyReceived.Set();
                }
            });

            Assert.IsTrue(replyReceived.Wait(TimeSpan.FromSeconds(15)), "Expected reply was not received");

            if (replyHandlerError != null)
            {
                Assert.Fail($"Failed to parse the reply payload: {replyHandlerError}");
            }

            Assert.AreEqual(expectedTemperature, replyValue);

            // Check via logs that the read read happened and was emitted
            testScenario.Utilities.WaitFor(15, "Expected controller logs not found after reply was received", () =>
            {
                var liveLog = controllerInstanceContext.Log;
                var escapedExpectedTemperature = Regex.Escape(expectedTemperature);

                var hasPropertyLog = liveLog.Any(log =>
                    Regex.IsMatch(log, $@"\|ReadTag\|.*\|getEquipmentProperties\] Emitting property value 'Temperature'='{escapedExpectedTemperature}'")
                );

                var hasRawLog = liveLog.Any(log =>
                    Regex.IsMatch(log, $@"\|ReadTag\|.*\|logMessage\] {escapedExpectedTemperature}")
                );

                return hasPropertyLog && hasRawLog;
            });
        }

For invoking a command, the test application needs to register in the scenario and the invoke the workflow in a way that calls the command. For example:

        [TestMethod]
        public void ExecuteCommandInCustomDriverDef()
        {
            #region Setup

            var controllerInstance = testContext.Instances["Controller"] as IControllerInstanceContext;
            var controllerInstanceLog = (controllerInstance as IInstanceContext).Log;

            #endregion Setup

            // Publish message bus message that is picked up by a workflow and calls an OPC-UA Command
            var mbClient = system.NewMessageBusClient();
            mbClient.Publish("Cmf.Test.OPCUA.ExecuteCustomCommand", new
            {
            });

            // Will call the "ns=2;s=Machines/Machine_1/StartMachine" command
            testScenario.Utilities.WaitFor(10, "Failed to execute command", () =>
            {
                return controllerInstanceLog.Any(log =>
                    Regex.IsMatch(log, $@"\|ExecuteCustomCommand\|.*\|logMessage\] Got Success on ExecuteCommand Output")
                );
            });

        }