Skip to content
Back to skills

tia-portal

ASecurity

Drive Siemens TIA Portal (V21, STEP 7 Professional, WinCC Unified) and a simulated S7-1500 (S7-PLCSIM Advanced) without hand clicking - create a project from SCL text files, add a CPU, compile and read the error list as text, load the simulated CPU, bring it to RUN, read and write its values, and build a WinCC Unified operator screen by script and run it in the browser. Use when the task is to build, change, inspect or test a TIA Portal project, an S7-1500 / S7-1200 program or a WinCC Unified...

  • 2 stars
  • 0 votes
  • 0 copies
  • 1 view
  • Added December 1, 2026
toolsgoshellbashawsgit

Works with

  • cli

Security analysis

A100/100

Pro scans all 8 files and shows the line behind each finding

Scanned December 1, 2026

npx -y skills add Maxxis20/tia-portal-skill --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of tia-portal?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for tia-portal
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/maxxis20-tia-portal/badge)](https://www.skillsdirectory.com/skills/maxxis20-tia-portal)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: tia-portal
description: Drive Siemens TIA Portal (V21, STEP 7 Professional, WinCC Unified) and a simulated S7-1500 (S7-PLCSIM Advanced) without hand clicking - create a project from SCL text files, add a CPU, compile and read the error list as text, load the simulated CPU, bring it to RUN, read and write its values, and build a WinCC Unified operator screen by script and run it in the browser. Use when the task is to build, change, inspect or test a TIA Portal project, an S7-1500 / S7-1200 program or a WinCC Unified screen, or when the user mentions TIA Portal, STEP 7, SCL, TIA Openness, PLCSIM, WinCC Unified, SIMATIC S7 or .ap21 files.
---

# TIA Portal, scripted

TIA Portal has an official programming interface, **TIA Openness** (.NET), and the simulated CPU of S7-PLCSIM
Advanced has one too. This skill keeps one PowerShell process attached to each ("hosts") and feeds them commands
as text. The project is made from files you write (SCL sources, a screen script); the tool compiles and loads;
the simulated CPU answers with values. The TIA window is on the screen all the time and shows what happens, but
nothing is clicked except the few things that have no interface (listed under "By hand").

`reference/findings.md` is what was found out on one installation (TIA Portal V21, Windows 11), each fact marked
**proven**, **seen** or **untested**. Read it when something does not behave as written here: the traps are there
with their symptoms. On another version, prove each step again.

## Setup

The scripts run on the Windows machine that has TIA Portal (Git Bash; nothing to set), or on another machine that
reaches it over ssh or through the guest agent of a Proxmox VM (`scripts/config.sh`).

On the TIA machine, once (how, and what goes wrong: `reference/findings.md`):

1. TIA Portal V21 with STEP 7 Professional and WinCC Unified, S7-PLCSIM V21 (brings PLCSIM Advanced), and for an
   operator screen WinCC Unified PC Runtime.
2. The Windows user at the screen is a member of the local groups `Siemens TIA Openness`, `PlcSimUsers` and
   `SIMATIC HMI`, and has logged on after that. (Setup adds the installing user; after a silent setup under
   another account nobody is in them.)
3. Licences, or the 21-day trials: see "By hand".
4. That user stays logged on at the console. TIA Portal needs a desktop; a remote desktop session takes the console
   away from the scripts. In a virtual machine: `reference/findings.md`, "virtual machines", before the first RUN.
5. `scripts/tia.sh net 192.168.10.2` (as administrator): the simulator's network adapter and the access point of
   the HMI runtime. Any private subnet that is not the office network; the CPU then gets 192.168.10.1.

## The loop

```
scripts/tia.sh start                      # TIA host: attaches to a running TIA Portal, else starts one (1-2 min)
scripts/tia.sh sim-start                  # simulator host, a process of its own
scripts/tia.sh status

scripts/tia.sh build <folder> [name]      # new project from the sources in <folder>/src: CPU 1511-1 PN, blocks, compile
scripts/tia.sh sim-on <name> 192.168.10.1 # a simulated CPU of that name, powered on, on the network
scripts/tia.sh load                       # hardware + program into it, CPU to RUN (about 10 s)
scripts/tia.sh sim '<powershell>'         # read and write its values: $sim
scripts/tia.sh sources <folder>           # after a change of the sources: blocks again, compile; then load

scripts/tia.sh hmi                        # add an operator panel (WinCC Unified) connected to the CPU
scripts/tia.sh run - < screen.ps1         # build tags and screen: $hmi, HmiTag, HmiItem, HmiBind, HmiScript, HmiEvent
scripts/tia.sh hmi-start                  # compile, load the local runtime, open the page; hmi-stop, hmi-state

scripts/tia.sh run '<powershell>' | -     # anything else through Openness: $tia $proj $dev $cpu $plc $hdev $hmi
scripts/tia.sh stop                       # both hosts (the simulated CPU powers off); TIA Portal stays open
```

- A host keeps its variables. `$global:x` set in one command is there in the next; so are `$proj`, `$cpu` ...
  after `build` (and after `start` when a project is open).
- One command at a time per host. When the wait ends before the command does, it goes on in the host:
  `tia.sh status`, look, ask again. Never send the same thing twice blindly (a second `build` is a second project).
- Output is text: compile and load results as a tree (state, counts, then every line that is not a success, with
  block and line number), errors as `ERROR <type>: <message>`.
- When something hangs, a dialog is waiting on the screen. `scripts/vm.sh shot` gives a screenshot path (Read it),
  `scripts/tia.sh dialog list` the windows, `dialog press "<title part>" "<button>"` answers one.
- `build`, `sources`, `load`, `hmi` and `hmi-start` may take up to five minutes at worst (usually one; a
  `build` of 1,800 source lines took 3.5 minutes): give them that time in your own tool. When your tool gave up
  waiting, the command still runs: `tia.sh last` (or `last sim`) says "still running" or prints its output.
- `tia.sh status` counts TIA Portal's processes: several for one open window is normal, 0 means it is gone.
- **Order that costs the least time**: write all sources first, then `start`, `sim-start`, `build`, `sim-on`,
  `load`; then `hmi`, the screen script, the hand step for a new panel, `hmi-start` once; then all tests in one
  file on fast time (`sim-speed 20`; keep TIA idle meanwhile, screen building on the same machine makes timed checks miss); last the clicks on the page and the pictures at real time. Look at the page
  once before the tests so that a second `hmi-start` is rare: each costs a minute.
- **Zero errors is the condition for a load, not the proof of the program.** The proof is values read from the
  CPU in each test state.

## SCL sources

One `.scl` file can hold several blocks; files are taken in name order (`10_blocks.scl`, `20_main.scl`): a block
must come after the blocks it uses. A block of the same name is replaced. When a source has an error, `build`
still leaves a project (with the blocks that did get through): correct the file and run `tia.sh sources`, not a
second `build`.

```
FUNCTION_BLOCK "FB_Count"
{ S7_Optimized_Access := 'TRUE' }
   VAR_INPUT
      Enable : Bool := TRUE;       // inputs with defaults are set values: writable from outside
   END_VAR
   VAR_OUTPUT
      Count : DInt;
   END_VAR
   VAR
      fbOther : "FB_Other";        // an instance of another block: declare it here, call it #fbOther(...)
      TS : Real; mem : LReal;
   END_VAR
BEGIN
   #TS := LIMIT(MN := 0.0, IN := LREAL_TO_REAL(RUNTIME(#mem)), MX := 1.0);   // seconds since the last call
   IF #Enable THEN
      #Count := #Count + 1;
   END_IF;
END_FUNCTION_BLOCK

DATA_BLOCK "Counter"               // instance data block: the values are Counter.Count, Counter.Enable
{ S7_Optimized_Access := 'TRUE' }
"FB_Count"
BEGIN
END_DATA_BLOCK

ORGANIZATION_BLOCK "Main"          // replaces the empty Main (OB1) of a new CPU
{ S7_Optimized_Access := 'TRUE' }
BEGIN
   "Counter"();
END_ORGANIZATION_BLOCK
```

Local variables carry `#`, global blocks quotes. A function returns through its own name with `#`:
`FUNCTION "FC_Curve" : Real` ... `#FC_Curve := ...;` (`"FC_Curve" := ...` is "Invalid assignment"). Real literals need the point (`0.0`). `LIMIT(MN:=, IN:=, MX:=)`,
`ABS`, `SQRT` exist. Names of data types and keywords cannot be variable names, in any case of letters: `Dt`
(DATE_AND_TIME), `n` and `rEf` (REF) were refused ("The specified value "Dt" is invalid", and the whole source then makes no block); use `dT_s`, `cnt`, `effRot`. Warnings "might not be initialized" for outputs that keep their value are harmless. `RUNTIME` gives nonsense on the first call: limit it. Keep everything an operator or a test
reads or writes in one instance data block: its members are then `Block.Member` for the simulator and
`"Block".Member` for the HMI.

## Ladder, FBD, tags, controller blocks

SCL is the short road. When the task asks for ladder (LAD) or function block diagram (FBD), write the block as a
**text document** `<name>.s7dcl` (one block per file, file name = block name) and put it in the source folder
beside the `.scl` files: `build` and `sources` take `*.scl`, `*.awl`, `*.s7dcl`, `*.xml` and `*.graph` in name
order.

```
{
    S7_Optimized := "TRUE";
    S7_PreferredLanguage := "LAD";
    S7_Version := "0.1"
}
FUNCTION_BLOCK "FB_Motor"
    VAR_INPUT
        Start : Bool;
        Stop : Bool;
    END_VAR
    VAR_OUTPUT
        Motor : Bool;
    END_VAR

    { S7_Language := "LAD" }
    NETWORK
        RUNG wire#powerrail
            Contact( #Start )
            wire#w1
            I_Contact( #Stop )
            Coil( #Motor )
        END_RUNG
        RUNG wire#powerrail
            Contact( #Motor )
        END_RUNG wire#w1
    END_NETWORK

    { S7_Language := "FBD" }
    NETWORK
        RUNG #Start
            O( in2 := #Motor )
            A( in2 := NOT #Stop )
            Coil( #Motor )
        END_RUNG
    END_NETWORK
END_FUNCTION_BLOCK
```

(The two networks do the same; a block normally has one of them.) A rung reads left to right; a second rung that
ends in `END_RUNG wire#w1` joins the first at `wire#w1`: a parallel branch. `I_Contact` is the normally closed
contact. In FBD the first input of each box is the signal coming from the left. An SCL block as a document has
`S7_EditorMode := "SCL"` in the header and `{ S7_Language := "SCL" }` networks; without one of the two header
lines the import says "Please use either 'S7_PreferredLanguage' or 'S7_EditorMode' pragma".

More instructions, the same in both languages unless said (all compiled on the CPU):

```
    VAR
        pi1 : "FB_PI";                 // your own block as a member: a multi-instance
        tmr : TON_TIME;
    END_VAR
    ...
        RUNG wire#powerrail            // ladder
            Contact( #Enable )
            #pi1( SP := #Sp, PV := #Pv, OUT => #Valve )                 // call of a function block; EN is the rung
            "FC_Curve"( x := #Tout, Ret_Val => #Sp )                    // call of a function, result in Ret_Val
            MOVE( in := #Pv, out1 => #Shown )
            { S7_Templates := "SrcType := Real" }
            GT_Contact( in1 := #Pv, in2 := 60.0 )                       // compare as a contact: GT_ GE_ LT_ LE_ EQ_ NE_
            { S7_Templates := "time_type := Time" }
            #tmr.TON( pt := T#5s, et => #Elapsed )                      // timer: the et pin must be written
            S_Coil( #Alarm )                                            // set; R_Coil resets; Coil assigns
        END_RUNG

        RUNG #Enable                   // FBD: starts with an operand, or with a box
            { S7_Templates := "time_type := Time" }
            #tmr.TON( pt := T#5s, et => #Elapsed )
            Coil( #Alarm )
        END_RUNG
        RUNG
            { S7_Templates := "SrcType := Real" }
            GT( in1 := #Pv, in2 := 60.0 )                               // FBD compare: GT GE LT LE EQ NE
            A( in2 := #Enable )
            Coil( #Alarm )
        END_RUNG
        RUNG
            ADD( in1 := #A, in2 := 1.0, out => #B )                     // SUB MUL DIV the same
        END_RUNG
```

- A box that works on a data type needs it named in the line before: `{ S7_Templates := "SrcType := Real" }` for
  a compare, `"time_type := Time"` for TON / TOF / TP. Without it the compile says "Please select a data type".
- Also compiled: `RUNG #x` before `MOVE(...)` in FBD (drives EN), `S_Coil` / `R_Coil` after an operand or a compare
  box, several branches joined on one `wire#w1`, negative literals (`-45.0`), defaults in declarations
  (`X : Real := 58.0;`). A long ladder or FBD block is quickest written by a small script of your own that
  prints the rungs.
- One block per file, every `NETWORK` closed by `END_NETWORK`, a ladder rung starts `RUNG wire#powerrail`, an FBD
  rung never has `wire#powerrail` ("Creation of part ... failed with RUNG 'Wire#powerrail'").
- The analog parts (PI, curve, filter) are easiest as SCL blocks called from the ladder or FBD sheet.
**Statement list (STL)**: a source file `<name>.awl`, taken like `.scl`:

```
FUNCTION_BLOCK "FB_Scale"
VERSION : 0.1
VAR_INPUT  X : Real; Start : Bool;  END_VAR
VAR_OUTPUT Y : Real; Over : Bool; Motor : Bool;  END_VAR
VAR  tmr : TON_TIME;  END_VAR
BEGIN
NETWORK
TITLE = scale and compare
      L #X;
      L 2.0;
      *R;
      T #Y;
      L #Y;
      L 100.0;
      >R;
      = #Over;
NETWORK
TITLE = start delay
      CALL #tmr
      (  IN := #Start, PT := T#5S, Q := #Motor );
END_FUNCTION_BLOCK
```

**Step sequences (GRAPH)**: TIA has no text form for GRAPH, the skill has one. Write `<name>.graph` beside the
other sources; `build` and `sources` turn it into the block (`scripts/graph.py`, its head has the full form):

```
GRAPH "Seq_Pump" 100                               // block name, block number
IN  Start : Bool
IN  Fb : Bool
IN  Trip : Bool
OUT Motor : Bool
OUT Valve : Bool
STEP Idle                                          // the first step is the initial step
STEP Opening
  N #Valve                                         // action: N while the step is active, S set, R reset
STEP Starting
  N #Valve
  N #Motor
  SUP #Starting.T > T#10s OR #Trip                 // supervision: when true the block reports a fault and holds the step
STEP Running
  N #Valve
  N #Motor
T Idle -> Opening : #Start AND NOT #Trip           // transition: contacts in series, NOT = normally closed
T Opening -> Starting : #Opening.T > T#3s          // time in the step; compares > < >= <= = <>
T Starting -> Running : #Fb
T Starting -> Idle : NOT #Start                    // a second transition from a step: alternative branch
T Running -> Idle : NOT #Start OR #Trip             // alternatives with OR
```

- Give it a data block and call it like any function block (in an `.scl` file that sorts after it):
  `DATA_BLOCK "Seq_Pump_DB" { S7_Optimized_Access := 'TRUE' } "Seq_Pump" BEGIN END_DATA_BLOCK`, then
  `"Seq_Pump_DB"();` in `Main`. It starts in automatic mode with the first step active.
- Read from the data block: `Seq_Pump_DB.S_NO` (number of the active step, in the order written),
  `Seq_Pump_DB.Running.X` (step active), `.Running.T` (time in the step), `Seq_Pump_DB.ERR_FLT`; write its inputs
  (`Seq_Pump_DB.Start`) or wire them in the call.
- Names the block keeps for itself cannot be your IN / OUT names, in any case of letters: `Fault`, `Error`,
  `Init`, `Auto`, `Man`, `Halt`, `Ack`, `Off` ... ("reserved for internal purposes"): use `Trip`, `Reset`.
- A supervision fault: `<DB>.ERR_FLT` is true, the sequence stays in the step (its `N` actions stay on: take the
  command away in your own code with `AND NOT ERR_FLT`) until a pulse on the input `ACK_EF`; `INIT_SQ` puts it back
  to the first step. `LOCK <condition>` in a step is its interlock.
- To leave a faulted step by an orderly stop instead of staying there: latch the alarm in your own code, pass it
  in as an input (`Abort`), end every alternative of the supervision with it (`SUP #Step.T > T#20s AND NOT #Abort`),
  give the step a transition `T Step -> Stopping : #Abort`, and pulse `ACK_EF`: the fault clears and the sequence
  goes down its stop branch.
- A condition is contacts and compares of one variable with a literal, joined by AND, alternatives by OR; any
  number of transitions may leave a step (four seen). No brackets, no compare of two variables, no `ABS`, no time
  from a variable, no action at step entry: compute such a condition in SCL and pass it in as a Bool.
- A comment starts with `//` (`#` is the mark of a local variable).
- A worked example with tests and screen: `examples/pump-sequence`.
- Not in the text form yet: simultaneous branches. Cause-effect matrix (CEM) blocks cannot be imported or
  exported at all.

- For an instruction you do not know the text of, let TIA show it: `tia.sh run "TiaExport '<block>' 'C:\<folder>'"`
  writes any block as `.s7dcl` and `.xml` (`vm.sh get` fetches them). Only the instructions shown above are
  proven as text. An instruction that no text guess gets right can be imported as `.xml` once and exported as
  text to read its form.
- `.xml` is TIA's own block format (SimaticML), one block per file; long, but it carries everything, such as an
  organization block of another kind (`<SecondaryType>CyclicInterrupt</SecondaryType>`, number 30 and up).
  Importing a `.s7dcl` over such a block turns it back into a program cycle block.
- PLC tags with addresses: `tia.sh run 'TiaTag Start Bool %I0.0; TiaTag Level Int %IW64'` (table `IO`).
- Siemens' controller block works as a member of your own block, no technology object needed:
  `pid : PID_Compact;` then `#pid(Setpoint := #SP, Input := #PV, Output => #Out);`. It starts in manual (`State`
  4, output 0): write `pid.Mode` = 3 and `pid.ModeActivate` = TRUE (from the test, or once in the program) for
  automatic. Its parameters are the members `pid.Retain.CtrlParams.*`. Timers the same way: `t1 : TON_TIME;`
  `#t1(IN := #x, PT := T#5S, Q => #y);`. Called from the program cycle here; Siemens asks for a cyclic interrupt
  block for a steady sampling time.

## MQTT

An S7-1500 has no MQTT client built in. Two roads:

- `examples/mqtt-publish`: `FB_Mqtt`, an MQTT 3.1.1 client in SCL over `TCON` / `TSEND` / `TRCV`. Publishes an
  `Array[*] of "MqttItem"` (topic, Real value) as `<Base>/<Topic>` every second, subscribes to `<Base>/set/#` and
  hands a received number out as `RxName` / `RxValue` / `RxNew`. No TLS, no login, QoS 0. Tested against Mosquitto
  on the simulator's network (22 of 22): the simulated CPU in TCP/IP mode reaches a broker on the PC's simulator
  adapter address directly.
- The Siemens library block `LMQTT_Client` (TLS, login, QoS): a download from Siemens Industry Online Support that
  needs a login; not tested here.

## Values and tests (simulator host)

```powershell
$sim.UpdateTagList()                             # after every load, else "NotUpToDate"
$sim.TagInfos | % { $_.Name + ' : ' + $_.DataType }
$sim.ReadFloat('Tank.Level'); $sim.ReadBool('Tank.PumpOn'); $sim.ReadInt32('Counter.Count')
$sim.WriteFloat('Tank.TestOutflow', [single]7.5); $sim.WriteBool('Tank.TestTrip', $true)
$sim.OperatingState                              # Off / Booting / Stop / Run
```

A test is: write the inputs, wait for the state you expect by reading in a loop with a time limit (and ask for
the state several readings in a row: a value may only be passing through), read the outputs, compare, print
PASS or FAIL with the numbers. Each test writes its own start state: values survive from the test before. A
control loop with a dead band rests anywhere inside it: "at the set value" is within the dead band plus a little.
Only what a command leaves on the pipeline comes back: `Write-Host` and `Out-Host` lines are lost, so end a loop
line with a plain string. Numbers come with a decimal point. Do not give your own functions one- or two-letter
names, nor a name that is a PowerShell alias (`compare`, `diff`, `sleep`, `sort`, `select`, `where`, `measure`,
`kill`, `type`, `write`, `echo`, `set`, `start`, `r`, `h`, `rm`, `ls`, `ps`, `sc` ...): the alias wins over the
function and the call does something else. Give them a prefix of your own (`DhCompare`). In .NET calls say the type
(`[math]::Max(18.0, $x)`).
Put the tests into a file and run it with `tia.sh sim ". 'C:\path\test.ps1'" 900`
(`scripts/vm.sh put <local> <windows path>` copies a file there). Any folder on the machine will do, for
instance the one `build` printed for the sources. Functions defined in a dot-sourced file stay in the host. If your own tool limits how long one
command may run (some move a command to the background after two or three minutes), define the test functions
once (`tia.sh sim ". 'C:\path\test.ps1'"`: the host keeps them) and call them one per command, each under
that limit.

**Run tests on fast time.** `tia.sh sim-speed 20` makes the simulated CPU's clock, timers and control loops run
twenty times as fast as the wall clock (proven at 10, 20 and 50: a loop that settles in 110 s settles in 6 s of
waiting, with the same numbers). Program, set values and time constants stay as documented, so nothing has to be
shortened and put back. Wait on the CPU's clock, never with `Start-Sleep` or `Get-Date`:

```powershell
$sim.WriteFloat('Tank.TestOutflow', [single]11)                                         # the step
$dip  = SimWait { $sim.ReadFloat('Tank.Level') -lt 48 } 120 0                         # CPU seconds until true; -1 = never
$back = SimWait { [Math]::Abs($sim.ReadFloat('Tank.Level') - 50) -lt 0.5 } 600 8     # true for 8 s without a break
$(if($back -ge 0){ 'PASS' } else { 'FAIL' }) + " outflow step: dip after $dip s, back after $back s, Valve " + $sim.ReadFloat('Tank.Valve')
SimSleep 30                                                                       # 30 s of the CPU's time
```

`SimWait` returns 0 when the condition holds from the first reading. `SimWait {condition} [seconds] [hold]` gives the limit generously (600 s of CPU time is 30 s of waiting): a slow
loop then passes with its real settling time instead of failing a guessed one. For something really slow (a
900 s filter needs about an hour of CPU time) use scale 50 or 100 for that test. `RUNTIME()` and the timers in the
program follow the fast clock. Keep slow filter and integrator states in `LReal`: with a cycle of a millisecond a
`Real` loses the small increments. At scale 20 a whole test set runs
in one command of a minute or two. `tia.sh sim-speed 1` before pictures of the page and at the end. A real CPU
has no such switch.

## Operator screen (WinCC Unified)

`tia.sh hmi` adds a Unified Comfort Panel (MTP1000, 1280x800), puts it on one subnet with the CPU and makes the
integrated connection. Then a script builds tags and screen through `$hmi`:

```powershell
HmiTag $hmi 'Level' '"Tank".Level' | Out-Null                    # HMI tag on a member of a data block (type comes along)
HmiTag $hmi 'PumpOn' '"Tank".PumpOn' | Out-Null
$old = $hmi.Screens.Find('Main'); if($old){ $old.Delete() }
$s = $hmi.Screens.Create('Main'); $s.Width = 1280; $s.Height = 800
HmiItem $s HmiText 't1' @{ Left=40; Top=20; Width=400; Height=26; Text='Tank 1'; ForeColor='#202020' } | Out-Null
$io = HmiItem $s HmiIOField 'v1' @{ Left=40; Top=60; Width=90; Height=30; IOFieldType='Output' }   # 'InputOutput': operator can type
HmiBind $io ProcessValue 'Level'
$p = HmiItem $s HmiCircle 'pump' @{ CenterX=300; CenterY=75; Radius=20; BackColor='#808080' }
HmiScript $p BackColor "return Tags('PumpOn').Read() ? 0xFF00B000 : 0xFFD02020;" @('PumpOn')        # colour by a tag
$b = HmiItem $s HmiButton 'b1' @{ Left=400; Top=56; Width=140; Height=36; Text='Pump trip' }
HmiEvent $b Tapped "Tags('TestTrip').Write(true);"
$r = HmiItem $s HmiRectangle 'f1' @{ Left=600; Top=50; Width=44; Height=44; BackColor='#F0F0F0'; ShowFillLevel=$true }
HmiBind $r FillLevel 'Valve'                                   # filled 0...100 %: a valve position, a level
HmiItem $s HmiLine 'l1' @{ X1=40; Y1=120; X2=640; Y2=120; LineColor='#C03030'; LineWidth=5 } | Out-Null
$hmi.RuntimeSettings.StartScreen = 'Main'
"items " + $s.ScreenItems.Count + ", findings " + @($s.Validate()).Count
TiaCompile $hdev; $proj.Save()
```

More parts, all seen working on the runtime page:

```powershell
$tc = HmiItem $s HmiTrendControl 'trend1' @{ Left=20; Top=20; Width=700; Height=360 }      # curves over time
$a = $tc.TrendAreas[0]; $a.Trends[0].DataSourceY.Source = 'Level'                           # first pen exists already
$t2 = $a.Trends.Create(); $t2.DataSourceY.Source = 'Valve'; $t2.LineColor = [Drawing.ColorTranslator]::FromHtml('#285AC8')
$a.BottomTimeAxes[0].TimeRangeFactor = 5                                                    # 5 minutes wide
$y = $a.LeftValueAxes[0]; $y.AutoScaling = $false; $y.BeginValue = 0; $y.EndValue = 100
HmiItem $s HmiAlarmControl 'alarms1' @{ Left=20; Top=400; Width=700; Height=300 } | Out-Null # list of active alarms
$al = $hmi.DiscreteAlarms.Create('Pump_trip'); $al.RaisedStateTag = 'PumpFault'; $al.AlarmClass = 'Alarm'
$al.EventText.Items[0].Text = '<body><p>Pump motor protection tripped</p></body>'
$an = $hmi.AnalogAlarms.Create('Level_high'); $an.RaisedStateTag = 'Level'; $an.Condition = 'UpperLimit'; $an.ConditionValue = 90
$c = HmiItem $s HmiCircle 'lamp' @{ CenterX=800; CenterY=60; Radius=22; BackColor='#D02020' }
$f = HmiGen $c.Dynamizations (HmiType 'FlashingDynamization') @('BackColor')                # flashing
$f.Color = [Drawing.ColorTranslator]::FromHtml('#E02020')    # its own colour, black by default: set both
$f.AlternateColor = [Drawing.ColorTranslator]::FromHtml('#5A5A5A'); $f.FlashingRate = 'Medium'; $f.FlashingCondition = 'Always'
# 'Always' flashes all the time. A lamp that flashes only on an alarm: a second item over a static one, flashing
# 'Always', with `Visible` bound to the alarm tag. A screenshot shows one phase of a flashing item: take several.
HmiBind $c Visible 'PumpFault'                                                              # shown only while the tag is true
HmiScript $r RotationAngle "return Tags('Valve').Read() * 0.9;" @('Valve')                  # turns with a value
HmiScript $m Left "return 780 + Tags('Level').Read() * 4;" @('Level')                       # moves with a value
$s.EventHandlers.Create([Enum]::Parse((HmiType 'HmiScreenEventType'), 'Loaded')).Script.ScriptCode =
  "let a = 0; HMIRuntime.Timers.SetInterval(function(){ if(Tags('PumpOn').Read()){ a = (a + 15) % 360; Screen.Items('fan').RotationAngle = a; } }, 100);"   # spins while the pump runs
HmiEvent $b Tapped "HMIRuntime.UI.SysFct.OpenScreenInPopup('pop1', 'Detail', true, 'Pump', 300, 300, false, undefined);"   # pop-up of screen 'Detail'
HmiEvent $b2 Tapped "HMIRuntime.UI.SysFct.ChangeScreen('Main', '~');"                       # other screen
HmiEvent $b3 Tapped "let t = Tags('TestTrip'); t.Write(!t.Read());"                         # toggle
$g = HmiItem $s HmiGauge 'g1' @{ Left=1000; Top=540; Width=220; Height=220 }; HmiBind $g ProcessValue 'Level'
```

- Several panels of the same kind: write one PowerShell function that draws a panel at an offset with a tag
  prefix, and call it once per panel.
- A text is centred in its box: `HorizontalTextAlignment='Left'` for labels. A rectangle with `ShowFillLevel`
  draws the filled part in its `BackColor` and the rest light: the colour of a valve or tank is its `BackColor`.
  It fills from the bottom up: make a position bar tall and narrow, a flat wide one shows only a stripe.
- Item names must be unique on the screen. A property that does not exist is named in the error with the list of
  those that do. Colours are `'#RRGGBB'`; in scripts `0xAARRGGBB`.
- Text: `Font.Size`, `Font.Weight`; a text has no `BackColor` (put a rectangle behind it), the screen has one.
  A number field's `OutputFormat` takes `{F1}`, `{F2}`, `{F3}`, `{I}` (`{F0}` is ignored: use `{I}`). A screen
  script may set an item's `Text`, `Top`, `Left`, `Visible`.
- A pop-up per device: one small screen per device (draw them with one function per kind of device: motor,
  valve, damper), opened by a click on the symbol (`Tapped`) with `OpenScreenInPopup` (seen working on the page:
  mode buttons, +/- steps, state, counters). One pop-up screen for many devices would need a faceplate type,
  which cannot be made by script.
- **Ready symbols** (Siemens' Industry Graphic Library, some 500: pumps, valves, motors, fans, blowers, heat
  exchangers, tanks, pipes, sensors, lamps, plus ISA-style symbols with state icons). Use them for devices instead
  of drawing with circles and rectangles: one item per device.
  ```powershell
  HmiWidgets                    # every symbol by group;   HmiWidgets Valve   # parameters of those that match
  $w = HmiWidget $s 'PumpSymbol' 'p1' @{ Left=440; Top=460; Width=66; Height=60; PumpType='1'; ShowBackground=$false;
         ShowSmallIndicator=$false; ShowIconLock=$false; ShowIconMaintenance=$false; ShowIconAlarm='3' }
  HmiScript $w ColorSymbol "let s = Tags('P1_ST').Read(); return s == 2 ? 0xFFD63B2F : (s == 1 ? 0xFF2E9E5B : 0xFF6B7783);" @('P1_ST')
  HmiScript $w ShowIconManual "return Tags('P1_MODE').Read() != 2;" @('P1_MODE')      # hand icon under the symbol
  HmiEvent  $w Tapped "HMIRuntime.UI.SysFct.OpenScreenInPopup('pop_P1', 'Pop_P1', true, 'P1', 860, 150, false, undefined);"
  $f = HmiWidget $s 'MotorVentilator' 'fan1' @{ Left=150; Top=170; Width=62; Height=62 }   # picture-style symbol: BasicColor
  HmiScript $f BasicColor "return Tags('Fan_Run').Read() ? 0xFF2E9E5B : 0xFFEEEEEE;" @('Fan_Run')
  ```
  A symbol's parameters (colours `'#RRGGBB'`, enums by number as text, booleans) take `HmiBind` and `HmiScript`
  like properties; `Tapped` on a symbol works (a click on the device opens its pop-up); a screen timer may turn
  it (`Screen.Items('fan1').RotationAngle = a`: a spinning fan). ISA symbols (`PumpSymbol ValveSymbol
  ThreeWayValveSymbol FlapValveSymbol MotorSymbol FilterSymbol CompressorSymbol ...`) keep a row for state icons
  under the symbol: the symbol fills about 0.7 of the width and height, so make the item wider than tall.
  `SymbolOrientation` '1' turns a valve by 90 degrees, `ActuatorType` '6' draws a motor actuator.
- More item types: HmiPolyline, HmiEllipse, HmiBar, HmiSlider, HmiToggleSwitch, HmiGauge. A circle has `CenterX
  CenterY Radius`, a line `X1 Y1 X2 Y2`, everything else `Left Top Width Height`.
- A screen cannot be imported from a file: it is built item by item, 0.2 to 0.4 s each, up to 0.9 s in a big
  project (200 items: one to three minutes; build one screen per command). Write the script so that
  it deletes and rebuilds its screen: then it can run again after every change.
- `tia.sh hmi-start` compiles the panel, loads the local runtime and opens `https://<computer name>/WebRH` in the
  browser. No login is asked in simulation. The page is the proof for people (`vm.sh shot`); for the test, press a
  button on the page (`vm.sh gui 'click x y'`, positions from the screenshot) and read the effect from the CPU.
  The page shows the panel 1:1 but shifted by the browser's frame (a few pixels right, some 80 down): take
  positions from the screenshot, not from the screen script. To type into an 'InputOutput' field: click it,
  Ctrl+A, the text, Enter.
- Each `hmi-start` opens one more browser tab; close an old one with `vm.sh gui 'keys ^1' 'keys ^w'`. When
  `gui 'front Siemens.Automation.Portal'` leaves the browser on top, `gui 'minimize msedge'` first. `hmi-start` takes about
  a minute; `sim-on` may sit for a minute at a licence notice it then answers itself.
- A field that is hatched and shows 0 has no data from the CPU: `tia.sh hmi-state` must say "S7 driver running:
  True"; else the three causes in `reference/findings.md`, "WinCC Unified".

## By hand

Things without an interface. Do them with `scripts/vm.sh shot` (look) and `scripts/vm.sh gui 'click x y' ...`
(positions from the screenshot you just took; say what you click), once per machine or per device:

- **Trial licences** (once per machine and product; skip with real licences). TIA offers them in a dialog
  "Automation License Management ... No valid License Key was found" with a list: click the entry, then Activate.
  It comes at the first licensed action in the window: portal view > Devices & networks > Add new device > open
  Controllers > SIMATIC S7-1500 (STEP 7), open HMI or PC systems > SIMATIC HMI application (WinCC Unified). After
  activating, add one such device in the window once (Add) and close the wizard it may open; only then do
  `tia.sh build` and `tia.sh hmi` get past "Necessary license ... is missing". PLCSIM Advanced asks at its first
  power-on (`tia.sh sim-on` reports state Off): `tia.sh dialog list`, the same kind of dialog, Activate, OK.
- **"Encrypted transfer" of a new HMI device.** Its first compile fails with "Runtime settings: The entered
  password does not comply ...": TIA must show the project view with the compile list, so first
  `tia.sh run '$hdev.ShowInEditor([Siemens.Engineering.HW.View]::Device)'`; then double-click that error line in
  the Info / Compile list; in the page that opens untick "Activate encrypted transfer"; compile again (`tia.sh run 'TiaCompile $hdev'`).
- **The browser's first-run pages** and "which app opens https" at the first `hmi-start`.
- The runtime page shows "Licenses are missing ... demo mode" with a Close button at each start, sometimes
  minutes after the page came up. It lies over the page and takes the next click: before a click on the page
  take a screenshot, close the notice if it is there, then click, and check the effect on the CPU.
- The compile of a new HMI device shows two error lines (password confirmation, password rules): either one opens
  the page. The browser may offer "Restore pages": close it.

## Rules

- Change the sources and the scripts and run them again; do not edit blocks or screens in the TIA window. The
  text is the program.
- After a change: compile, read the tree, load, test by values. Then the screen.
- Say what was tested on what. A simulated CPU is not a real one: say so in the report and list what was not
  tested.
- Power the simulated CPU off when it is not needed (`tia.sh stop sim`): it takes a processor core all the time.
- A wrong argument to Openness can end TIA Portal ("NonRecoverableException", then every call fails on a null
  object): `tia.sh status` shows "TIA Portal processes: 0"; `tia.sh stop tia`, `tia.sh start`, open the project
  again (`tia.sh run "TiaOpen 'C:\Users\<user>\Documents\Automation\<name>\<name>.ap21'"`). Save (`$proj.Save()`)
  before experiments; `build` saves at its end.
- Never write to a real controller with this skill unless the user named that controller and asked for it.

## Where things are

| | |
|---|---|
| `scripts/tia.sh` | all verbs above |
| `scripts/vm.sh` | the machine: `ps` (PowerShell as administrator, no desktop), `ui` (in the desktop session), `put`, `get`, `shot`, `gui` (mouse and keys: `click x y`, `dclick`, `keys`, `text`, `front <process>`) |
| `scripts/win/host.ps1` | the two hosts and their helpers: `svc`, `msgs`, `TiaBuild`, `TiaSources`, `TiaExport`, `TiaTag`, `TiaCompile`, `TiaLoad`, `TiaHmi`, `TiaOpen`, `Hmi...`, `SimOn`, `SimUp`, `[TiaCb]` |
| `scripts/win/dialog.ps1`, `rt.ps1`, `net.ps1` | dialogs by name; the HMI runtime (Runtime Manager command line); adapter and access point |
| `reference/findings.md` | every proven fact, the traps with their symptoms, what is not tested |

Files in this skill

  • SKILL.md33.9 KB
  • examples/README.md50 B
  • reference/findings.md37.3 KB
  • scripts/config.sh1.6 KB
  • scripts/graph.py13.1 KB
  • scripts/graph_pattern.xml43.5 KB
  • scripts/tia.sh10.2 KB
  • scripts/vm.sh11.3 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in tools →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.