# Emulating PLC logic with Open Industry Project

A line's control logic can be written and proved on an emulated plant before anyone wires a real
cabinet. [Open Industry Project](https://www.openindustryproject.org/) (OIP, MIT licence) is a free
simulator of conveyors, sensors, wrappers and robots with real physics and its own IEC 61131-3 PLC,
and its desktop app lets an AI assistant build a line, write its Structured Text and run tests on it.
Naga then mirrors the same line as a model and reads the running OIP line live over OPC UA, so the
model and the emulated plant check each other.

| Tool | The question it answers |
|---|---|
| Naga | How much the line carries: rates, buffers, how many machines, with confidence intervals |
| OIP | Whether the control logic works: interlocks, sequences and handshakes on a physics line |
| Naga's twin reading OIP | Whether the model and the emulated line agree, minute by minute |

The rest of this page follows one line from an empty OIP scene to a Naga twin that reads it.

## What you need

The desktop app is the part that matters, because only it serves the assistant's tools and the
OPC UA server. The browser version of OIP has neither.

- **OIP desktop** for Windows or Linux, from [openindustryproject.org](https://www.openindustryproject.org/).
- **nagasim** with the OPC UA reader and the MCP server: `pip install "nagasim[opcua,mcp]"`.
- **An assistant** that speaks MCP, such as Claude Code. In OIP, **Settings > Agent connections**
  turns its server on; then `claude mcp add --transport http oip http://127.0.0.1:5189/mcp`.
- **The skill** `emulating-plc-logic-in-oip`, which ships with the engine and the `naga` plugin
  beside `simulation-study`; `naga skill --copy DIR` puts both in an assistant's skills folder. It holds the order of work, the traps below and a worked example.

With these in place an assistant can do every step below, and a person can do each one by hand
in OIP's editor.

## Build and prove the logic in OIP

OIP's tools are the only way to lay a line out: its placement engine seats each conveyor and sensor
and checks every parameter, so a hand-written scene file skips both. The assistant works in this
order, and each step has a check.

1. **Read the guide.** `get_guide` gives the units, the tags, the Structured Text dialect and the
   test format; `get_package` gives each part's frame and tags.
2. **Lay it out.** `add_part`, then `snap_part` (or `add_part` with `onto`) butts conveyors together
   and seats eyes on guards. `get_problems` then lists only tags the program does not handle yet.
3. **Program it.** `set_program` takes the whole Structured Text and answers with its compile
   problems. Declare what the program reads as `VAR_INPUT` and what it commands as `VAR_OUTPUT`.
4. **Test the outcome.** `run_test` steps the physics and the PLC for a set number of simulated
   seconds, presses inputs at set times and evaluates checks. 400 simulated seconds take about one.
   When the case the logic guards never arises at the normal feed, force it with a fault on the
   station or a burst of arrivals, or the test cannot tell good logic from bad.
5. **Prove the test can fail.** Break one rung and run it again: it must fail. Then restore the
   program and keep the test with `save_test`.

A stretch-wrap line shows what such a program looks like. Pallets ride an infeed into the
wrapper's station, one at a time, stop under the arm, are wrapped and leave on an outfeed.

```text
Running := (Start OR Running) AND NOT Stop;
IF EyeWas AND NOT InfeedEye THEN Occupied := TRUE; END_IF;   (* a pallet entered the station *)
EyeWas := InfeedEye;
CASE Step OF
  0: IF InPos THEN Step := 1; END_IF;                        (* centred under the arm *)
  1: IF WrapBusy THEN Step := 2; END_IF;
  2: IF WrapDone THEN Step := 3; Wraps := Wraps + 1; END_IF;
  3: IF NOT InPos THEN Step := 0; Occupied := FALSE; END_IF; (* it has left *)
END_CASE;
SpawnerRun := Running;
InfeedRun := Running AND NOT (InfeedEye AND Occupied);       (* one pallet at a time *)
StationRun := Running AND (Step = 0 OR Step = 3);
OutfeedRun := Running;
WrapStart := Running AND Step = 1 AND NOT WrapBusy;          (* one rising edge a pallet *)
```

Its test asserts outcomes, not only tags: pallets ship, every shipped pallet was wrapped, and the
station both stops and runs again. In one run it passed with 9 pallets wrapped and 9 shipped in
400 simulated seconds, and it failed as soon as the station's hold was removed, so it proves the hold.

```json
{"name": "pallets are wrapped one at a time and shipped", "duration": 400,
 "inputs": [{"at": 0.5, "tag": "Start", "value": true}, {"at": 1, "tag": "Start", "value": false}],
 "checks": [
  {"tag": "SinkCount", "eventually": true, "min": 3},
  {"tag": "Wraps", "always": true, "min": {"tag": "SinkCount"}},
  {"tag": "StationRun", "eventually": true, "equals": false},
  {"tag": "StationRun", "eventually": true, "from": 300, "equals": true},
  {"tag": "WrapBusy", "eventually": true, "equals": true}]}
```

## Mirror the line in Naga

A model of the line is only as good as the numbers it takes from it, and OIP can measure them. Trace
the wrapper's busy tag in a `run_test` for its cycle time, and read the distances from the spawner to
the wrap axis and from the axis to the exit. In the line above the wrap took 27.8 s, and the belts ran
4.7 m in and 5.5 m out at 0.4 m/s.

The model is then a CREATE (gaps drawn from 25 to 75 s, as OIP's spawner draws them), a CONVEYOR of
4.7 m, a PROCESS of 27.8 s for the wrapper, a CONVEYOR of 5.5 m and a DISPOSE. It gave 53.4 s a pallet
from arrival to exit against about 54 s in OIP, so the model and the emulated line agree to within a
second.

## Read the line live

The running OIP line can feed a Naga twin through OIP's OPC UA server. Ticking **Publish the
program's variables** in OIP's PLC panel starts the server on this machine, on the port the panel
shows (4843 by default), without security and for anonymous sessions; no tool can tick it for you.
Each program variable is the node `ns=1;s=<name>`, `SpawnCount` for instance.

The connection is yours, in your connections file, never the model's (see [Live data](live-data.md)):

```json
{"format": 1, "connections": {"oip": {"kind": "opcua", "url": "opc.tcp://127.0.0.1:4843",
  "private": true, "root": "ns=1;"}}}
```

The model names it in a data source, and a [plant mapping](plant-timeline.md) turns OIP's two
counters into the counters of two blocks:

```json
"data_sources": [{"name": "oip", "kind": "opcua", "connection": "oip",
  "location": "ns=1;s=SpawnCount\nns=1;s=SinkCount", "options": {"interval_ms": 100}}]
```

```json
{"format": 1, "time": {"epoch": "1970-01-01T00:00:00+00:00", "unit": "seconds"},
 "signals": [
  {"source": "oip", "key": "ns=1;s=SpawnCount", "as": "counter", "block": "Pallets in"},
  {"source": "oip", "key": "ns=1;s=SinkCount", "as": "counter", "block": "Outfeed"}]}
```

Check the mapping, start the line in OIP and press its Start, then run the twin:

```console
naga plant check map.json wrap_line.json
naga twin run wrap_line.json --map map.json --connections connections.json --out twin --horizon 300 --every 15s --forecast-every 30s --max-cycles 40
```

Forecasts run every 5 minutes unless `--forecast-every` says otherwise, so a short run sets it. Each
forecast prints `forecast ok`, and the twin's counters follow OIP's tags box for box. The reader
only subscribes: it writes no node and calls no method, so nothing in Naga can change the
emulated PLC.

## What to expect

A twin fed by counters alone knows how many parts came in and went out, not where each part is. Its
forecasts therefore start from an empty line: exits run about the work in progress low, and every
cycle warns `W_STATE_NOT_COVERED`, which is expected. `naga plant check` also warns `W_PLANT_EPOCH`
for the 1970 epoch: live readings are stamped in Unix seconds, so it only means times do not read
as dates. Map `at` or `seen` signals as well when you want the parts' places.

Typed conveyors (a `type` and a `path`) start from the plant like plain ones, unless they have stops,
diverts or merges, which a state cannot carry yet; such a model is still monitored, and its forecast
is refused by name (`E_TWIN_STATE`). nagasim 0.21 and earlier refuse every typed conveyor, so
use plain conveyors (`length`, `speed`, `spacing`) there.

## Traps found on a real line

These came up while building the line above in OIP desktop 0.1.0, and each one cost a run to find.

- OIP's stretch wrapper conveys along its own -Z axis: for a line along +X give it a `rotationY`
  of -pi/2, or the load stalls against the column.
- A spawner whose product is `oip.unit-load` counts its spawns but makes no cargo; a pallet-sized
  `oip.box` works.
- OIP's live simulation nearly stops while its window is minimised or covered, and `capture_view`
  then returns an old picture: keep the window visible for a live run. `run_test` is not affected.
- A single `set_tag` write to Stop was once lost, cause unknown: hold Stop with `force_tag`, and
  after pressing Start check that `Running` latched.
- OIP's live simulation runs on wall-clock time, while `run_test` is deterministic and fast: prove
  logic with `run_test`, and keep the live run for the twin.

## Limits

OIP is in early development, and its PLC engine is still being checked against other IEC 61131-3
implementations, so a program's behaviour can change between its versions. Its tools and its OPC UA
server need the desktop app open on a window, one project at a time, and connecting OIP to a real
or soft PLC is a person's step in its PLC panel. Within those limits it gives Naga a physics plant on
your own machine, with no hardware, broker or licence to buy.
