Virtual Commissioning Testing: Validate PLC and Robot Programs Before You Touch the Hardware

Virtual Commissioning Testing: Validate PLC and Robot Programs Before You Touch the Hardware

Commissioning a production line is expensive. A single day of downtime on a modern automotive assembly line costs anywhere from $500,000 to $2 million. When a PLC program has a logic error that only surfaces during physical commissioning — after the steel has been bolted down and the cables have been run — that cost lands on your project budget.

Virtual commissioning flips the sequence. You run your PLC and robot programs against a software simulation of the plant before the physical build is complete. Bugs get found on a workstation, not on the shop floor. This article covers how to build a real testing strategy around virtual commissioning: what to test, how to automate it, and how to reconcile virtual results with physical outcomes.

What Virtual Commissioning Actually Is

Virtual commissioning (VC) is the practice of connecting real control software — PLC programs, robot programs, SCADA logic — to a 3D simulation model of the plant (called a virtual plant model or digital twin) and running it as if it were the physical system.

The control software does not know it is talking to a simulation. It reads sensor values from the model, executes its logic, and writes actuator commands back. The model responds physically — conveyors move, robots follow trajectories, safety zones trigger. Engineers watch for logic errors, sequencing bugs, race conditions, and timing issues before a single bolt is tightened on the real machine.

The communication layer between the real controller and the virtual plant is typically OPC Unified Architecture (OPC-UA), the IEC 62541 standard for industrial device communication. The virtual model exposes the same OPC-UA node structure as the real hardware. The PLC does not care which end it is talking to.

Key tools in this space:

  • Factory I/O — a 3D simulation environment for industrial automation, purpose-built for PLC testing
  • Siemens NX / Process Simulate — enterprise-grade virtual commissioning platforms
  • ABB RobotStudio / KUKA.OfficeLite / FANUC ROBOGUIDE — robot-specific offline programming and simulation
  • PLCopen — a standards body that defines function block libraries and test frameworks for PLC software
  • CODESYS Test Manager — unit and integration test tooling for IEC 61131-3 programs

The OPC-UA Interface Layer

Before you can test anything, you need to understand the OPC-UA node structure your PLC exposes. Every tag — conveyor speed, sensor state, alarm bit — is an OPC-UA node with a NodeId. Your tests read and write these nodes to simulate sensor inputs and observe actuator outputs.

Here is a minimal Python OPC-UA client using the opcua library to connect to a simulation server and run a basic I/O test:

import time
import unittest
from opcua import Client, ua

OPCUA_SERVER_URL = "opc.tcp://localhost:4840/freeopcua/server/"

# Node IDs from the PLC project — match your actual address space
NODE_CONVEYOR_RUN     = "ns=2;i=1001"
NODE_SENSOR_PART_PRESENT = "ns=2;i=1002"
NODE_CONVEYOR_SPEED   = "ns=2;i=1003"
NODE_ALARM_ESTOP      = "ns=2;i=1004"
NODE_CONVEYOR_RUNNING = "ns=2;i=1005"  # feedback bit from PLC


class TestConveyorSequence(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.client = Client(OPCUA_SERVER_URL)
        cls.client.connect()
        # Give the simulation model time to initialise
        time.sleep(0.5)

    @classmethod
    def tearDownClass(cls):
        cls.client.disconnect()

    def _write(self, node_id: str, value):
        node = self.client.get_node(node_id)
        dv = ua.DataValue(ua.Variant(value, node.get_data_type_as_variant_type()))
        node.set_value(dv)

    def _read(self, node_id: str):
        return self.client.get_node(node_id).get_value()

    def test_conveyor_starts_when_commanded(self):
        """PLC should assert CONVEYOR_RUNNING within one scan cycle after RUN command."""
        self._write(NODE_CONVEYOR_RUN, True)
        time.sleep(0.1)  # allow at least one PLC scan cycle
        self.assertTrue(
            self._read(NODE_CONVEYOR_RUNNING),
            "CONVEYOR_RUNNING not asserted after RUN command"
        )

    def test_conveyor_stops_on_estop(self):
        """E-stop input must de-energise conveyor within 100 ms (safety requirement)."""
        self._write(NODE_CONVEYOR_RUN, True)
        time.sleep(0.1)
        self._write(NODE_ALARM_ESTOP, True)  # simulate E-stop pressed
        time.sleep(0.1)
        self.assertFalse(
            self._read(NODE_CONVEYOR_RUNNING),
            "Conveyor still running after E-stop — SAFETY CRITICAL FAILURE"
        )
        # Clean up
        self._write(NODE_ALARM_ESTOP, False)
        self._write(NODE_CONVEYOR_RUN, False)

    def test_speed_within_spec_under_load(self):
        """Conveyor speed should stay within ±5% of setpoint when a part is present."""
        SETPOINT = 500  # mm/s
        self._write(NODE_CONVEYOR_SPEED, SETPOINT)
        self._write(NODE_CONVEYOR_RUN, True)
        self._write(NODE_SENSOR_PART_PRESENT, True)  # simulate part on belt
        time.sleep(0.3)
        actual_speed = self._read(NODE_CONVEYOR_SPEED)
        tolerance = SETPOINT * 0.05
        self.assertAlmostEqual(
            actual_speed, SETPOINT, delta=tolerance,
            msg=f"Speed {actual_speed} outside ±5% of setpoint {SETPOINT}"
        )

    def test_no_run_command_while_estop_active(self):
        """PLC must ignore RUN command while E-stop is latched."""
        self._write(NODE_ALARM_ESTOP, True)
        self._write(NODE_CONVEYOR_RUN, True)
        time.sleep(0.1)
        self.assertFalse(
            self._read(NODE_CONVEYOR_RUNNING),
            "PLC accepted RUN command while E-stop was active"
        )
        self._write(NODE_ALARM_ESTOP, False)
        self._write(NODE_CONVEYOR_RUN, False)


if __name__ == "__main__":
    unittest.main()

A few things to note about this pattern:

Timing is not optional. PLC scan cycles are typically 1–20 ms. If you read a feedback bit 1 ms after writing a command, the PLC may not have executed a scan yet. Build explicit delays or — better — poll with a timeout loop.

Node IDs must match both environments. The simulation server and the real PLC must expose the same OPC-UA address space. If they diverge, your tests are testing the wrong thing. Keep node IDs in a shared configuration file, not hardcoded.

Use real data types. OPC-UA is strongly typed. Writing a Python int to a node that expects a UINT16 will either fail silently or raise an exception depending on the server. Always specify the variant type explicitly.

PLC Logic Testing in Structured Text

The IEC 61131-3 standard defines five PLC programming languages. Structured Text (ST) is the most testable because it reads like Pascal and supports modular function blocks. Here is a simplified conveyor control function block with its corresponding PLCopen-style test structure:

(* ConveyorControl.st — IEC 61131-3 Structured Text *)

FUNCTION_BLOCK ConveyorControl
VAR_INPUT
    bRunCmd      : BOOL;   (* Operator run command *)
    bEStop       : BOOL;   (* Emergency stop, NC contact — TRUE = fault *)
    bSensorPart  : BOOL;   (* Part-present sensor *)
    rSpeedSetpt  : REAL;   (* Speed setpoint, mm/s *)
END_VAR
VAR_OUTPUT
    bRunning     : BOOL;   (* Conveyor drive energised *)
    bFault       : BOOL;   (* Fault latch *)
    rSpeedActual : REAL;   (* Simulated actual speed *)
END_VAR
VAR
    bEStopLatch  : BOOL;
    rRampState   : REAL;
END_VAR

(* E-stop latch — must be reset explicitly *)
IF bEStop THEN
    bEStopLatch := TRUE;
END_IF;

(* Drive logic *)
IF bEStopLatch THEN
    bRunning     := FALSE;
    bFault       := TRUE;
    rSpeedActual := 0.0;
ELSIF bRunCmd THEN
    bRunning := TRUE;
    (* Simple ramp simulation for virtual model *)
    IF rRampState < rSpeedSetpt THEN
        rRampState := rRampState + 50.0;   (* 50 mm/s per scan *)
    END_IF;
    rSpeedActual := rRampState;
ELSE
    bRunning     := FALSE;
    rRampState   := 0.0;
    rSpeedActual := 0.0;
END_IF;

(* Reset latch only when E-stop is cleared AND run command is low *)
IF NOT bEStop AND NOT bRunCmd THEN
    bEStopLatch := FALSE;
    bFault      := FALSE;
END_IF;

END_FUNCTION_BLOCK

And the corresponding test function block using CODESYS Test Manager conventions:

(* TC_ConveyorControl.st — PLCopen test cases *)

FUNCTION_BLOCK TC_ConveyorControl EXTENDS TcUnit.FB_TestSuite
VAR
    fbConveyor : ConveyorControl;
END_VAR

METHOD PRIVATE Test_NormalStart
    fbConveyor(bRunCmd:=TRUE, bEStop:=FALSE, rSpeedSetpt:=500.0);
    AssertTrue(
        Condition := fbConveyor.bRunning,
        Message   := 'Conveyor must run when commanded and E-stop clear'
    );
    AssertFalse(
        Condition := fbConveyor.bFault,
        Message   := 'No fault expected during normal run'
    );
END_METHOD

METHOD PRIVATE Test_EStopPreventsStart
    (* Ensure latch is clear first *)
    fbConveyor(bRunCmd:=FALSE, bEStop:=FALSE);
    (* Now activate E-stop and try to run *)
    fbConveyor(bRunCmd:=TRUE, bEStop:=TRUE);
    AssertFalse(
        Condition := fbConveyor.bRunning,
        Message   := 'Conveyor must not run while E-stop is active'
    );
    AssertTrue(
        Condition := fbConveyor.bFault,
        Message   := 'Fault must be set when E-stop triggers'
    );
END_METHOD

METHOD PRIVATE Test_EStopLatchPersistsAfterClear
    (* Trigger E-stop *)
    fbConveyor(bRunCmd:=FALSE, bEStop:=TRUE);
    (* Clear E-stop but immediately try to run — latch should hold *)
    fbConveyor(bRunCmd:=TRUE, bEStop:=FALSE);
    AssertFalse(
        Condition := fbConveyor.bRunning,
        Message   := 'E-stop latch must hold until explicit reset sequence'
    );
END_METHOD

METHOD FB_init : BOOL
    Test_NormalStart();
    Test_EStopPreventsStart();
    Test_EStopLatchPersistsAfterClear();
END_METHOD

END_FUNCTION_BLOCK

The latch test (Test_EStopLatchPersistsAfterClear) is the kind of edge case that kills physical commissioning. The logic looks correct when you read it, but the reset condition is subtle: the latch only clears when both bEStop is FALSE and bRunCmd is FALSE. If an operator clears the E-stop and immediately hits run, the machine stays stopped. On a real line this causes a confusing fault that takes 20 minutes to diagnose. In the virtual model it surfaces in 200 ms.

Factory I/O Integration Testing

Factory I/O connects to PLC simulators (Siemens S7-PLCSIM, CODESYS SoftPLC, Modbus TCP, OPC-UA) and provides a 3D physics model of the plant. You can script it via its OPC-UA server to drive automated test scenarios.

A typical integration test workflow:

  1. Reset scene — write all sensor nodes to their resting state (no parts present, all actuators de-energised)
  2. Start PLC program — confirm the PLC initialises without faults
  3. Inject a part — write the part-present sensor TRUE, or trigger the virtual part spawner
  4. Assert the sequence — verify each step of the PLC sequence fires in order within timing tolerances
  5. Inject a fault — simulate a jammed sensor or motor overload
  6. Assert fault handling — verify the correct alarm activates and the machine goes to a safe state
import time
from opcua import Client

FACTORY_IO_SERVER = "opc.tcp://localhost:4840"

def reset_scene(client):
    """Return all I/O to resting state."""
    nodes_to_reset = {
        "ns=2;s=Sensor.PartPresent":   False,
        "ns=2;s=Sensor.ConveyorEmpty": True,
        "ns=2;s=Output.ConveyorRun":   False,
        "ns=2;s=Output.SorterExtend":  False,
    }
    for node_id, value in nodes_to_reset.items():
        client.get_node(node_id).set_value(value)
    time.sleep(0.2)

def run_part_through_conveyor(client):
    """Integration test: part enters, conveyor runs, sorter fires at exit."""
    reset_scene(client)

    # Step 1: Start system
    client.get_node("ns=2;s=Input.SystemRun").set_value(True)
    time.sleep(0.1)

    # Step 2: Inject part at entry sensor
    client.get_node("ns=2;s=Sensor.PartPresent").set_value(True)
    time.sleep(0.5)  # allow conveyor travel time in simulation

    # Step 3: Assert part arrived at exit
    exit_sensor = client.get_node("ns=2;s=Sensor.PartAtSorter").get_value()
    assert exit_sensor, "Part did not reach sorter sensor — conveyor sequence failed"

    # Step 4: Sorter should have extended
    sorter_state = client.get_node("ns=2;s=Output.SorterExtend").get_value()
    assert sorter_state, "Sorter did not extend when part arrived"

    print("PASS: Part-through-conveyor integration test")

if __name__ == "__main__":
    client = Client(FACTORY_IO_SERVER)
    client.connect()
    try:
        run_part_through_conveyor(client)
    finally:
        client.disconnect()

Automated Regression Testing for PLC Logic

Once you have a working test suite, the next step is running it automatically on every PLC program change. The workflow mirrors software CI/CD:

  1. Engineer commits a PLC project change to version control (Git works with CODESYS projects exported as XML)
  2. CI pipeline launches the SoftPLC simulator with the new program
  3. Python test suite connects over OPC-UA and executes all test cases
  4. Results are reported as pass/fail with timing data
  5. If any test fails, the commit is blocked from reaching the production PLC

A minimal GitHub Actions pipeline for CODESYS projects looks like this:

name: PLC Regression Tests

on: [push, pull_request]

jobs:
  plc-tests:
    runs-on: [self-hosted, windows, codesys]  # Needs a Windows runner with CODESYS installed
    steps:
      - uses: actions/checkout@v4

      - name: Start CODESYS SoftPLC with project
        run: |
          & "C:\Program Files\CODESYS 3.5\Common\CODESYS.exe" `
            --noUI `
            --project "${{ github.workspace }}\plc\ConveyorSystem.project" `
            --run
        shell: powershell

      - name: Wait for PLC to initialise
        run: Start-Sleep -Seconds 5
        shell: powershell

      - name: Run OPC-UA test suite
        run: python -m pytest tests/plc/ -v --tb=short
        env:
          OPCUA_SERVER_URL: "opc.tcp://localhost:4840"

      - name: Stop SoftPLC
        if: always()
        run: Stop-Process -Name "CODESYS" -Force -ErrorAction SilentlyContinue
        shell: powershell

Self-hosted runners are necessary here because the PLC runtime must be installed locally — you cannot spin up CODESYS in a Docker container (licensing and Windows dependencies make this impractical today).

Comparing Virtual vs Real Commissioning Outcomes

Virtual commissioning reduces physical commissioning time but does not eliminate it. The gap between virtual and physical results comes from a predictable set of sources:

Network jitter and scan-cycle variance. The virtual model runs at simulation speed, not real time. An OPC-UA node update that takes 2 ms in simulation may take 12 ms on the real network. Build timing tolerances into your assertions — do not hardcode exact millisecond values.

Sensor noise and real-world physics. A virtual part-present sensor is binary. A real inductive proximity sensor has hysteresis, a switching window, and can be affected by vibration. Tests that pass cleanly in simulation may fail intermittently on the real line due to sensor chatter. When you see this, the fix is usually debounce logic in the PLC — add a test case for it.

Mechanical tolerances. The virtual model assumes perfect geometry. A conveyor belt that is 2 mm narrower than specified will jam parts that sail through the simulation. This is physical commissioning territory, not a software bug — but your timing-based tests will surface it as a timing failure.

PLC firmware differences. CODESYS SoftPLC and a real Siemens S7-1500 do not execute identical instruction sets. Integer overflow, floating-point rounding, and task preemption behaviour can differ. Test on the target hardware family whenever possible.

A useful practice is maintaining a delta log: a structured record of every test case that passed in virtual commissioning but failed during physical commissioning, with root cause. After three or four projects, patterns emerge. Common patterns become additional virtual test cases. The gap between virtual and physical shrinks with each project iteration.

What Good Coverage Looks Like

A mature virtual commissioning test suite for a mid-complexity cell (one robot, two conveyors, four sensors, one vision system) typically contains:

  • Unit tests (PLCopen / CODESYS Test Manager): 40–80 function block tests covering all logic branches, including fault states and edge cases
  • Integration tests (OPC-UA Python suite against Factory I/O or equivalent): 15–30 scenario tests covering full part-flow sequences, fault injection, and recovery sequences
  • Timing tests: 5–10 tests asserting that safety-critical responses (E-stop, light curtain) occur within the specified reaction time
  • Regression baseline: all of the above run automatically on every PLC program commit

The investment pays back on the first project. A typical physical commissioning for a cell of this complexity takes 5–10 days on site. Teams with mature virtual commissioning suites routinely compress physical commissioning to 1–2 days, spending the rest in the simulation where mistakes are free.

Getting Started

If you are starting from scratch, the lowest-friction path is:

  1. Install Factory I/O (30-day free trial, $99/year thereafter) and CODESYS Control Win (free SoftPLC for Windows)
  2. Write a simple conveyor program in Structured Text
  3. Connect Factory I/O to CODESYS over OPC-UA using the built-in driver
  4. Write three Python test cases using opcua-asyncio or the synchronous opcua library
  5. Run the tests manually, then wire them into a CI pipeline

The discipline of writing tests first — before the PLC logic exists — forces you to specify the exact behaviour you expect from the machine before you implement it. That specification becomes the commissioning acceptance criteria. When the physical machine passes the same tests the simulation passed, you have documented, reproducible evidence that the system meets its specification.

That is a different conversation to have with a customer than "we tested it on site and it seemed fine."

Read more

Start now free