Files
lmxopcua/docs/Driver.TwinCAT.Cli.md

254 lines
11 KiB
Markdown

# `otopcua-twincat-cli` — Beckhoff TwinCAT test client
Ad-hoc probe / read / write / subscribe tool for Beckhoff TwinCAT 2 / TwinCAT 3
runtimes via ADS. Uses the **same** `TwinCATDriver` the OtOpcUa server does
(`Beckhoff.TwinCAT.Ads` package). Native ADS notifications by default;
`--poll-only` falls back to the shared `PollGroupEngine`.
Fifth (final) of the driver test-client CLIs.
## Build + run
```powershell
dotnet run --project src/ZB.MOM.WW.OtOpcUa.Driver.TwinCAT.Cli -- --help
```
## Prerequisite: AMS router
The `Beckhoff.TwinCAT.Ads` library needs a reachable AMS router to open ADS
sessions. Pick one:
1. **Local TwinCAT XAR** — install the free TwinCAT 3 XAR Engineering install
on the machine running the CLI; it ships the router.
2. **Beckhoff.TwinCAT.Ads.TcpRouter** — standalone NuGet router. Run in a
sidecar process when no XAR is installed.
3. **Remote AMS route** — any Windows box with TwinCAT installed, with an AMS
route authorised to the CLI host.
The CLI compiles + runs without a router, but every wire call fails with a
transport error until one is reachable.
## UDT decomposition
PR 4.1 (issue #315) replaces the old "skip non-atomic symbols" behaviour
of `BrowseSymbolsAsync` with a recursive type walker
(`TwinCATTypeWalker`). When the OtOpcUa server's TwinCAT driver runs
discovery with `EnableControllerBrowse=true`, struct / UDT / function-block
typed symbols flatten into one OPC UA variable per atomic leaf. Browse
addresses use the same dotted-instance form the PLC exposes:
| PLC declaration | OPC UA browse paths surfaced |
|---|---|
| `MAIN.bStart : BOOL` | `MAIN.bStart` |
| `GVL.stMotor : ST_Motor` | `GVL.stMotor.bRunning`, `GVL.stMotor.nState`, `GVL.stMotor.rTemperature`, … |
| `GVL.aRecipe : ARRAY[1..10] OF DINT` | `GVL.aRecipe[1]``GVL.aRecipe[10]` |
| `GVL.aPairs : ARRAY[0..2] OF ST_Pair` | `GVL.aPairs[0].nCount`, `GVL.aPairs[0].rValue`, `GVL.aPairs[1].…` |
| `GVL.aBig : ARRAY[1..5000] OF DINT` | `GVL.aBig` (single whole-array root — over the cap) |
The CLI's `read` / `write` / `subscribe` commands take dotted paths
directly:
```powershell
# Read a struct member
otopcua-twincat-cli read -n 192.168.1.40.1.1 -s GVL.stMotor.rTemperature -t Real
# Read an array element
otopcua-twincat-cli read -n 192.168.1.40.1.1 -s "GVL.aRecipe[3]" -t DInt
```
### Array expansion bound
`TwinCATDriverOptions.MaxArrayExpansion` (default `1024`) caps how many
elements an array contributes to the discovered address space. Arrays
whose total element count exceeds the cap surface as a single
whole-array root with `IsArrayRoot=true` instead of one variable per
element. Raise the bound when operators routinely care about individual
elements of large recipe / lookup tables; lower it to keep discovery
cheap for symbol tables that ship multi-thousand-element scratch
arrays. Pre-declared whole-array tags from the `Tags` config bypass the
walker entirely — set `ArrayDimensions` on a `TwinCATTagDefinition` to
keep array reads on the existing PR 1.4 read-array path.
### Cycle / depth guard
The walker tracks the visited-type set + a hard depth cap of 8 levels
so a self-pointer (`POINTER TO ST_Self`) or pathological alias chain
terminates rather than spinning. POINTER / REFERENCE members are
skipped at the type-graph level — surfacing them would require
dereferencing through the AMS routing layer which has its own access
patterns.
## Common flags
| Flag | Default | Purpose |
|---|---|---|
| `-n` / `--ams-net-id` | **required** | AMS Net ID (e.g. `192.168.1.40.1.1`) |
| `-p` / `--ams-port` | `851` | AMS port (TwinCAT 3 PLC = 851, TwinCAT 2 = 801) |
| `--timeout-ms` | `5000` | Per-operation timeout |
| `--poll-only` | off | Disable native ADS notifications, use `PollGroupEngine` instead |
| `--verbose` | off | Serilog debug output |
## Data types
TwinCAT exposes the IEC 61131-3 atomic set: `Bool`, `SInt`, `USInt`, `Int`,
`UInt`, `DInt`, `UDInt`, `LInt`, `ULInt`, `Real`, `LReal`, `String`, `WString`,
`Time`, `Date`, `DateTime`, `TimeOfDay`. The four IEC time/date variants
marshal as `UDINT` on the wire — CLI takes a numeric raw value and lets the
caller interpret semantics.
## Commands
### `probe`
```powershell
# Local TwinCAT 3, probe a canonical global
otopcua-twincat-cli probe -n 127.0.0.1.1.1 -s "TwinCAT_SystemInfoVarList._AppInfo.OnlineChangeCnt"
# Remote, probe a project variable
otopcua-twincat-cli probe -n 192.168.1.40.1.1 -s MAIN.bRunning --type Bool
```
#### Health probe
The OtOpcUa server's TwinCAT driver runs an internal probe loop (PR 3.2, issue #314)
that — alongside the cheap `ReadStateAsync` reachability check — samples four
well-known system symbols once per probe interval and surfaces the result through
the cross-driver `driver-diagnostics` RPC (added for Modbus, task #154). The same
symbols can be probed directly via the CLI for ad-hoc troubleshooting:
```powershell
# Cycle time (UDINT, 100 ns ticks → ÷10000 for ms)
otopcua-twincat-cli probe -n 192.168.1.40.1.1 -s "TwinCAT_SystemInfoVarList._TaskInfo[1].CycleTime" --type UDInt
# Last task execution wall-clock (UDINT, 100 ns ticks → ÷10000 for ms)
otopcua-twincat-cli probe -n 192.168.1.40.1.1 -s "TwinCAT_SystemInfoVarList._TaskInfo[1].LastExecTime" --type UDInt
# Online-change count — increments on every accepted online change
otopcua-twincat-cli probe -n 192.168.1.40.1.1 -s "TwinCAT_SystemInfoVarList._AppInfo.OnlineChangeCnt" --type UDInt
# Loaded PLC project name (STRING(80))
otopcua-twincat-cli probe -n 192.168.1.40.1.1 -s "TwinCAT_SystemInfoVarList._AppInfo.AppName" --type String
```
Within the running OtOpcUa server these four signals land on
`DeviceState.LastDiagnostics` as a `TwinCATDeviceDiagnostics` record + are folded
into `DriverHealth.Diagnostics` keyed `TwinCAT.CycleTimeMs`, `TwinCAT.LastExecTimeMs`,
`TwinCAT.JitterMs` (computed `LastExecTimeMs - CycleTimeMs`),
`TwinCAT.OnlineChangeCnt`, and `TwinCAT.OnlineChangeIncrements`. See
`docs/drivers/TwinCAT-Test-Fixture.md §Diagnostics` for the full mapping.
### `read`
```powershell
# Bool symbol
otopcua-twincat-cli read -n 192.168.1.40.1.1 -s MAIN.bStart -t Bool
# Counter
otopcua-twincat-cli read -n 192.168.1.40.1.1 -s GVL.Counter -t DInt
# Nested UDT member
otopcua-twincat-cli read -n 192.168.1.40.1.1 -s Motor1.Status.Running -t Bool
# Array element
otopcua-twincat-cli read -n 192.168.1.40.1.1 -s "Recipe[3]" -t Real
# WString
otopcua-twincat-cli read -n 192.168.1.40.1.1 -s GVL.sMessage -t WString
```
ADS variable handles for `read` / `write` symbols are cached transparently
inside the CLI's underlying `AdsTwinCATClient`. The first read of a symbol
resolves a handle; repeats reuse the cached handle for smaller AMS payloads
and skipped name resolution. The cache wipes on reconnect, on
`DeviceSymbolVersionInvalid` (with a one-shot retry), and on CLI exit. See
`docs/drivers/TwinCAT-Test-Fixture.md §Handle caching` for the full story
including the staleness caveat after an online change.
### `write`
```powershell
otopcua-twincat-cli write -n 192.168.1.40.1.1 -s MAIN.bStart -t Bool -v true
otopcua-twincat-cli write -n 192.168.1.40.1.1 -s GVL.Counter -t DInt -v 42
otopcua-twincat-cli write -n 192.168.1.40.1.1 -s GVL.sMessage -t WString -v "running"
```
Structure writes refused — drop to driver config JSON for those.
### `subscribe`
```powershell
# Native ADS notifications (default) — PLC pushes on its own cycle
otopcua-twincat-cli subscribe -n 192.168.1.40.1.1 -s GVL.Counter -t DInt -i 500
# Fall back to polling for runtimes where native notifications are constrained
otopcua-twincat-cli subscribe -n 192.168.1.40.1.1 -s GVL.Counter -t DInt -i 500 --poll-only
# Coalesce bursty changes — runtime buffers up to 500 ms before dispatch
otopcua-twincat-cli subscribe -n 192.168.1.40.1.1 -s GVL.Counter -t DInt -i 50 --max-delay-ms 500
```
| Flag | Default | Purpose |
|---|---|---|
| `-s` / `--symbol` | **required** | Symbol path — same format as `read` |
| `-t` / `--type` | `DInt` | IEC type (see Data types section) |
| `-i` / `--interval-ms` | `1000` | **Cycle time** — minimum interval between change checks the PLC runtime applies |
| `--max-delay-ms` | `0` | **Max coalescing window** — upper bound on how long the runtime buffers change events before dispatch. `0` = fire ASAP, no coalescing |
| `--poll-only` | off | Disable native notifications, use `PollGroupEngine` instead |
`-i` / `--interval-ms` and `--max-delay-ms` are different things and both flow
into the Beckhoff `NotificationSettings` ctor:
- **`--interval-ms`** is the *cycle*: the runtime checks for value changes at
most this often. Smaller = lower latency, higher CPU.
- **`--max-delay-ms`** is the *coalescing ceiling*: once a change is detected,
the runtime can hold it for up to this long before dispatching, which lets
it batch a burst of changes into a single callback. Default `0` means
every detected change fires immediately — same as the pre-PR-3.1 behaviour.
For high-frequency signals (a counter incrementing every 10 ms PLC cycle),
pair a small `-i` (so latency stays bounded) with a non-zero `--max-delay-ms`
(so the OPC UA queue downstream doesn't flood). For slow signals just leave
`--max-delay-ms` at `0`.
The subscribe banner announces which mechanism is in play — "ADS notification"
or "polling" — and includes the `max-delay` value when set, so it's obvious
in screen-recorded bug reports.
`--poll-only` polls go through the same cached-handle path as `read`, so
repeated polls of the same symbol carry only a 4-byte handle on the wire
rather than the full symbolic path.
### `alarms` (PR 5.1 / #316)
Stream TC3 EventLogger alarms via the driver's `IAlarmSource` bridge.
Subscribes against AMS port 110 (`AMSPORT_EVENTLOG`) on the same target,
prints each event with timestamp / source / severity / message until
Ctrl+C.
```powershell
# All alarms — every event the EventLogger surfaces
otopcua-twincat-cli alarms -n 192.168.1.40.1.1
# Filter by source — only events whose source name matches (case-insensitive)
otopcua-twincat-cli alarms -n 192.168.1.40.1.1 --source Conveyor1.MotorOverload
# Multiple sources — repeat the flag
otopcua-twincat-cli alarms -n 192.168.1.40.1.1 --source Conveyor1 --source Pump3
```
| Flag | Default | Purpose |
|---|---|---|
| `--source` | (none) | Optional source filter; repeat for multiple |
Output format (one line per event):
```
[HH:mm:ss.fff] <source> sev=<Low|Medium|High|Critical> type=<event-class> cond=<condition-id> "<message>"
```
The verb forces `EnableAlarms=true` on the underlying driver; the
default driver config keeps it off so deployments without an
EventLogger configured pay no cost. See
[`docs/drivers/TwinCAT.md` §Alarms](drivers/TwinCAT.md) for the
full bridge architecture and decode caveats.