Program Structure API
Tier: Stable Core
Program/rung builders and control-flow composition primitives.
pyrung.Program
Container for PLC logic (rungs and subroutines).
Used as a context manager to capture rungs
with Program() as logic: with rung(Button): out(Light)
Also works with PLC
runner = PLC(logic)
check
check(
*,
select: set[str] | None = None,
ignore: set[str] | None = None,
extend_select: set[str] | None = None,
dt: float = 0.01,
) -> ValidationReport
Run core ladder checks and return their findings.
select and ignore accept complete rule codes or categories.
dt configures the physical-realism checks.
dataview
Return a chainable query over this program's tag dependency graph.
The graph is built lazily on first call and cached.
pyrung.rung
Rung class for the immutable PLC engine.
Rungs contain conditions and instructions. They evaluate within a ScanContext for batched updates.
Rung
A rung of ladder logic.
Contains conditions (contacts) and instructions (coils). Evaluation is done within a ScanContext for batched updates.
Conditions are ANDed together - all must be true for instructions to execute.
add_instruction
Add an instruction to execute when conditions are true.
A box with pins (:meth:Instruction.has_pins) ends its rung: it is
refused beside any other output of the rung's wire tree (the trunk and
every branch), as CLICK draws its pins from the box's own wire.
add_branch
Add a nested branch (parallel path) to this rung.
Refused where it would put a box with pins beside another output (see
:meth:add_instruction).
sp_tree
Return this rung's condition structure as an SP tree.
Returns None for unconditional rungs (no conditions).
evaluate
Evaluate this rung within a ScanContext.
Writes are batched in the context and committed at scan end. Each
instruction solves only the path from the rail to it. The trunk's
contacts are read once, and that power is held for everything under
it. Each branch's own contacts are read when execution reaches the
branch, so they see the writes of the instructions above it. A
.continued() rung is a rung of its own, and its contacts are read
live like any other's.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctx
|
ScanContext
|
ScanContext for reading/writing with batched updates. |
required |
execute
Execute this rung's rows in solve order with the provided power state.
Each branch is solved when the loop reaches it (_solve_row). Its
own contacts are read live, under enabled, which is the power held for
the rows under this one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ctx
|
ScanContext
|
Live ScanContext for instruction read-after-write. |
required |
enabled
|
bool
|
Whether this rung/branch is powered. |
required |
dsl_call
Return count_up(), the call that the author wrote to build instruction.
instruction is an instruction or the name of its class. Messages print this instead of the class name, which the author never typed. An instruction class from outside pyrung keeps its class name, because no pyrung call builds it.
pyrung.program
Program and Rung context managers for the immutable PLC engine.
Provides DSL syntax for building PLC programs:
with Program() as logic:
with rung(Button):
out(Light)
runner = PLC(logic)
math
module-attribute
Math instruction (CLICK's Math): math(expression, dest, *, oneshot=False).
Evaluates expression and stores it in dest, truncated to the destination's width (modular wrapping). Division by zero gives 0; decimal or hex mode is inferred from the tags read.
CountDownBuilder
Bases: _BuilderBase
Builder for count_down instruction with chaining API.
Supports required .reset() chaining: count_down(Counter[1], preset=-25).reset(reset_tag)
reset
Add reset condition (required).
When reset condition is true, sets the accumulator to 0 and clears the done bit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*conditions
|
Condition | Tag | tuple[Condition | Tag, ...] | list[Condition | Tag]
|
Condition(s) for resetting the counter. |
()
|
Returns:
| Type | Description |
|---|---|
Tag
|
The done bit tag. |
CountUpBuilder
Bases: _BuilderBase
Builder for count_up instruction with chaining API.
Supports optional .down() and required .reset() chaining: count_up(Counter[1], preset=100).reset(reset_tag) count_up(Counter[1], preset=50).down(down_cond).reset(reset_tag)
down
down(
*conditions: Condition
| Tag
| tuple[Condition | Tag, ...]
| list[Condition | Tag],
) -> CountUpBuilder
Add down trigger (optional).
Creates a bidirectional counter that increments on rung true and decrements on down condition true.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*conditions
|
Condition | Tag | tuple[Condition | Tag, ...] | list[Condition | Tag]
|
Condition(s) for decrementing the counter. |
()
|
Returns:
| Type | Description |
|---|---|
CountUpBuilder
|
Self for chaining. |
reset
Add reset condition (required).
When reset condition is true, clears both done bit and accumulator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*conditions
|
Condition | Tag | tuple[Condition | Tag, ...] | list[Condition | Tag]
|
Condition(s) for resetting the counter. |
()
|
Returns:
| Type | Description |
|---|---|
Tag
|
The done bit tag. |
OffDelayBuilder
Bases: _AutoFinalizeBuilderBase
Builder for off_delay instruction (TOF behavior, Click-style).
Auto-resets when re-enabled.
OnDelayBuilder
Bases: _AutoFinalizeBuilderBase
Builder for on_delay instruction with optional .reset() chaining (Click-style).
Without .reset(): TON behavior (auto-reset on rung false, shares its rung) With .reset(): RTON behavior (manual reset required, ends its rung)
reset
Add reset condition (makes timer retentive - RTON).
When reset condition is true, clears both done bit and accumulator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*conditions
|
Condition | Tag | tuple[Condition | Tag, ...] | list[Condition | Tag]
|
Condition(s) for resetting the timer. |
()
|
Returns:
| Type | Description |
|---|---|
Tag
|
The done bit tag. |
ShiftBuilder
Branch
Context manager for a parallel branch within a rung.
A branch executes when both the parent rung conditions AND the branch's own conditions are true.
Example
with rung(Step == 0): out(Light1) with branch(AutoMode): # Only executes if Step==0 AND AutoMode out(Light2) copy(1, Step, oneshot=True)
ForLoop
Context manager for a repeated block of body rungs within a rung.
Program
Container for PLC logic (rungs and subroutines).
Used as a context manager to capture rungs
with Program() as logic: with rung(Button): out(Light)
Also works with PLC
runner = PLC(logic)
check
check(
*,
select: set[str] | None = None,
ignore: set[str] | None = None,
extend_select: set[str] | None = None,
dt: float = 0.01,
) -> ValidationReport
Run core ladder checks and return their findings.
select and ignore accept complete rule codes or categories.
dt configures the physical-realism checks.
dataview
Return a chainable query over this program's tag dependency graph.
The graph is built lazily on first call and cached.
Rung
Context manager for defining a rung.
Example
with rung(Button): out(Light)
with rung(Step == 0): out(Light1) copy(1, Step, oneshot=True)
continued
Mark this rung as a continuation of the previous rung.
This is the import form of a CLICK rung saved with several wires. The export draws a continued rung as a CLICK rung of its own. The rung is solved like a rung of its own, so its contacts see every write above them, including the prior rung's. The prior rung must be in the same execution scope (main or the current subroutine).
Returns:
| Type | Description |
|---|---|
Rung
|
self, for chaining: |
Subroutine
Context manager for defining a subroutine.
Subroutines are named blocks of rungs that are only executed when called.
Example
with subroutine("my_sub"): with rung(): out(Light)
SubroutineFunc
A decorated function that represents a subroutine.
Created by using @subroutine("name") as a decorator. When passed to call(), auto-registers with the current Program on first use.
Example
@subroutine("init") def init_sequence(): with rung(): out(Light)
with Program() as logic: with rung(Button): call(init_sequence)
ForbiddenControlFlowError
Bases: RuntimeError
Raised when Python control flow is used inside strict DSL scope.
count_down
Count Down instruction (CTD).
Creates a counter that counts down on the rising edges of the rung
condition (as a CLICK does), from 0. Done is True while acc <= preset, so
a positive preset is done from the start; stage acc above the preset with
copy() to count down to it.
Example
with rung(Dispense): count_down(Counter[1], preset=-25).reset(Reload)
A box with pins: it ends its rung. Requires .reset() chaining.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
counter
|
DoneAccUDT
|
Counter instance (must have |
required |
preset
|
Tag | int
|
Target value (Tag or int). |
required |
Returns:
| Type | Description |
|---|---|
CountDownBuilder
|
Builder for chaining .reset(). |
count_up
Count Up instruction (CTU).
Creates a counter that counts the rising edges of the rung condition (as a CLICK does): one count each time it goes True, however long it stays True. Done is True while acc >= preset.
Example
with rung(PartSensor): count_up(Counter[1], preset=100).reset(ResetBtn)
A box with pins: it ends its rung. Requires .reset() chaining.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
counter
|
DoneAccUDT
|
Counter instance (must have |
required |
preset
|
Tag | int
|
Target value (Tag or int). |
required |
Returns:
| Type | Description |
|---|---|
CountUpBuilder
|
Builder for chaining .down() and .reset(). |
debounce
debounce(
target: Tag,
*,
on: tuple[DoneAccUDT, Tag | int],
off: tuple[DoneAccUDT, Tag | int],
unit: TimeUnitStr = "ms",
) -> Tag
Debounce coil (CLICK Out, Debounce).
The target follows the rung once the rung has held steady: it turns on
after the rung has been true for the on time and off after it has been
false for the off time. CLICK requires both sides.
Example
with rung(LevelSwitch): debounce(TankFull, on=(Timer[1], 500), off=(Timer[2], 200))
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
Tag
|
Bool tag driven by the coil. |
required |
on
|
tuple[DoneAccUDT, Tag | int]
|
|
required |
off
|
tuple[DoneAccUDT, Tag | int]
|
|
required |
unit
|
TimeUnitStr
|
Time unit for both presets (default |
'ms'
|
flasher
flasher(
target: Tag,
*,
on: tuple[DoneAccUDT, Tag | int],
off: tuple[DoneAccUDT, Tag | int],
unit: TimeUnitStr = "ms",
) -> Tag
Flasher coil (CLICK Out, Flasher).
While the rung is true the target alternates: on for the on time, then
off for the off time, starting with the on phase. The rung going false
turns it off at once.
Example
with rung(Alarm): flasher(Beacon, on=(Timer[3], 500), off=(Timer[4], 500))
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
Tag
|
Bool tag driven by the coil. |
required |
on
|
tuple[DoneAccUDT, Tag | int]
|
|
required |
off
|
tuple[DoneAccUDT, Tag | int]
|
|
required |
unit
|
TimeUnitStr
|
Time unit for both presets (default |
'ms'
|
off_delay
Off-Delay Timer instruction (TOF).
Done bit is True while enabled. After disable, counts until preset, then done bit goes False. Auto-resets when re-enabled.
Example
with rung(MotorCommand): off_delay(Timer[2], preset=10000) off_delay(Timer[2], 10, "s") # 10 seconds
Off-delay timers are composable in-rung (no pins, so they share their rung).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timer
|
DoneAccUDT
|
Timer instance (must have |
required |
preset
|
Tag | int
|
Delay time in time units (Tag or int). |
required |
unit
|
TimeUnitStr
|
Time unit for accumulator (default: |
'ms'
|
Returns:
| Type | Description |
|---|---|
OffDelayBuilder
|
Builder for the off_delay instruction. |
on_delay
On-Delay Timer instruction (TON/RTON).
Accumulates time while rung is true.
Example
with rung(MotorRunning): on_delay(Timer[1], preset=5000) # TON keyword on_delay(Timer[1], 5000) # TON positional on_delay(Timer[1], 5, "s") # TON 5 seconds on_delay(Timer[1], preset=5000).reset(ResetBtn) # RTON
Without .reset(), this is TON and remains composable in-rung. With .reset(), this is RTON, a box with pins, and it ends its rung.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timer
|
DoneAccUDT
|
Timer instance (must have |
required |
preset
|
Tag | int
|
Target value in time units (Tag or int). |
required |
unit
|
TimeUnitStr
|
Time unit for accumulator (default: |
'ms'
|
Returns:
| Type | Description |
|---|---|
OnDelayBuilder
|
Builder for optional .reset() chaining. |
shift
Shift register instruction builder.
Data input comes from current rung power. Use .clock(...) then .reset(...) to finalize and add the instruction.
Example
with rung(DataBit): shift(C.select(2, 7)).clock(ClockBit).reset(ResetBit)
time_event_drum
time_event_drum(
*,
outputs: Sequence[Tag],
presets: Sequence[Tag | int | None],
events: Sequence[Condition | Tag | None],
unit: TimeUnitStr = "ms",
pattern: Sequence[Sequence[bool | int]],
current_step: Tag,
accumulator: Tag,
completion_flag: Tag,
) -> TimeEventDrumBuilder
CLICK's Time & Event drum: each step ends when its time is up and its event is on.
A step's preset or event may be None (event-only or time-only step), not both.
Events are levels, unlike event_drum's rising edges: an event already on
when the time comes up ends the step on that scan. The accumulator keeps
counting while a timed step waits for its event.
timed
timed(
target: Tag,
timer: DoneAccUDT,
preset: Tag | int,
unit: TimeUnitStr = "ms",
*,
maintained: bool = False,
) -> Tag
Timed coil (CLICK Out, Timed).
A rung edge turns the target on for preset. Not maintained, it then
goes off even if the rung is still true, and the next pulse needs the rung
to go false and true again. Maintained, it stays on for at least
preset and then follows the rung.
Example
with rung(CallButton): timed(Horn, Timer[5], 1000) timed(Lamp, Timer[6], 3, "sec", maintained=True)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
Tag
|
Bool tag driven by the coil. |
required |
timer
|
DoneAccUDT
|
Timer instance that times the on time. |
required |
preset
|
Tag | int
|
On time in |
required |
unit
|
TimeUnitStr
|
Time unit (default |
'ms'
|
maintained
|
bool
|
Keep the target on while the rung stays true after the on time. |
False
|
toggle
Toggle coil (CLICK Out with Toggle).
Inverts the target on each OFF->ON transition of the rung and keeps its value while the rung is false.
Example
with rung(PushButton): toggle(Light) toggle(Y[1].immediate)
And
And(
*conditions: Condition
| Tag
| ImmediateRef
| tuple[Condition | Tag | ImmediateRef, ...]
| list[Condition | Tag | ImmediateRef],
) -> AllCondition
AND condition - true when all sub-conditions are true.
This is equivalent to comma-separated rung conditions, but useful when building grouped condition trees with Or().
Example
with rung(And(Ready, AutoMode)): out(StartPermissive)
with rung(Or(And(Ready, AutoMode), RemoteStart)): out(StartPermissive)
Or
OR condition - true when any sub-condition is true.
Use this to combine multiple conditions with OR logic within a rung. Multiple conditions passed directly to rung() are ANDed together.
Example
with rung(Step == 1, Or(Start, CmdStart)): out(Light) # True if Step==1 AND (Start OR CmdStart)
Grouped AND inside OR (explicit):
with rung(Or(Start, And(AutoMode, Ready), RemoteStart)): out(Light)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conditions
|
Condition | Tag | ImmediateRef
|
Conditions to OR together. |
()
|
Returns:
| Type | Description |
|---|---|
AnyCondition
|
AnyCondition that evaluates True if any sub-condition is True. |
fall
Falling edge contact (FE).
True only on 1->0 transition. Requires PLC to track previous values.
Example
with rung(fall(Button)): reset(MotorRunning) # Resets when button is released
rise
Rising edge contact (RE).
True only on 0->1 transition. Requires PLC to track previous values.
Example
with rung(rise(Button)): latch(MotorRunning) # Latches on button press, not while held
branch
Create a parallel branch within a rung.
A branch executes when both the parent rung conditions AND the branch's own conditions are true.
Example
with rung(Step == 0): out(Light1) with branch(AutoMode): # Only executes if Step==0 AND AutoMode out(Light2) copy(1, Step, oneshot=True)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conditions
|
ConditionTerm
|
Conditions that must be true (in addition to parent rung) for this branch's instructions to execute. |
()
|
Returns:
| Type | Description |
|---|---|
Branch
|
Branch context manager. |
comment
Attach a comment to the next rung.
The comment is consumed by the immediately following rung() constructor.
Must be called inside a Program context.
Example::
comment("UnitMode Change")
with rung(C_UnitModeChgRequest):
copy(1, C_UnitModeChgRequestBool, oneshot=True)
forloop
Create a repeated block context.
A bare instruction in the body is an always-true body rung. A body rung
with contacts is written as with rung(...) inside the loop. Its
contacts are evaluated on every iteration. Loops nest up to three deep,
each with its own loop.idx.
As on CLICK, a false loop rung skips the body. Its coils hold and its
one-shots do not re-arm. A tag count is read once. An Int is read as
unsigned 16-bit, so -1 runs 65535 iterations. A Dint is read whole and
signed, so 65536 runs 65536 iterations, and 0 or below runs none. A
constant is read whole, so forloop(70000) runs 70000.
Example
with rung(Enable): with forloop(10) as loop: copy(Source[loop.idx + 1], Dest[loop.idx + 1]) with rung(Fault): break_loop()
subroutine
Define a named subroutine.
Subroutines are only executed when called via call(). They are NOT executed during normal program scan.
Example
with Program() as logic: with rung(Button): call("my_sub")
with subroutine("my_sub"):
with rung():
out(Light)
program
program(
fn: Callable[[], None] | None = None,
/,
*,
strict: bool = True,
) -> Program | Callable[[Callable[[], None]], Program]
Decorator to create a Program from a function.
Example
@program def my_logic(): with rung(Button): out(Light)
@program(strict=False) def permissive_logic(): with rung(Button): out(Light)
runner = PLC(my_logic)
blockcopy
blockcopy(
source: Any,
dest: Any,
*,
convert: CopyConverter | None = None,
oneshot: bool = False,
) -> None
Block copy instruction.
Copies values from source BlockRange to dest BlockRange. Both ranges must have the same length.
Pass convert=to_value or convert=to_ascii for text→numeric
block conversion. Only value and ascii modes are supported.
Example
with rung(CopyEnable): blockcopy(DS.select(1, 10), DD.select(1, 10))
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Any
|
Source BlockRange or IndirectBlockRange from .select(). |
required |
dest
|
Any
|
Dest BlockRange or IndirectBlockRange from .select(). |
required |
convert
|
CopyConverter | None
|
Optional converter (to_value or to_ascii only). |
None
|
oneshot
|
bool
|
If True, execute only once per rung activation. |
False
|
break_loop
Leave the innermost forloop now; the scan continues after the loop.
Must sit in a body rung with a contact (CLICK Break).
Example
with rung(Enable): with forloop(10) as loop: with rung(Fault): break_loop()
calc
Deprecated. Use math(), CLICK's name for the Math instruction.
call
Call a subroutine instruction.
Executes the named subroutine when the rung is true. Accepts either a string name or a @subroutine-decorated function.
Example
with rung(Button): call("init_sequence")
with subroutine("init_sequence"): with rung(): out(Light)
Or with decorator:
@subroutine("init") def init_sequence(): with rung(): out(Light)
with Program() as logic: with rung(Button): call(init_sequence)
continue_loop
Skip the rest of this forloop iteration and start the next one.
Must sit in a body rung with a contact (CLICK Continue).
Example
with rung(Enable): with forloop(10) as loop: with rung(Src[loop.idx] == 0): continue_loop() copy(Src[loop.idx], Dst[loop.idx])
copy
copy(
source: Any,
target: Tag | IndirectRef | IndirectExprRef,
*,
convert: CopyConverter | None = None,
oneshot: bool = False,
) -> Tag | IndirectRef | IndirectExprRef
Copy instruction (CPY/MOV).
Copies source value to target. Pass convert= for text/numeric
conversion (see :mod:pyrung.core.copy_converters).
Example
with rung(Button): copy(5, StepNumber)
end_early
End this scan of the main program here. This is CLICK's conditional END.
The rungs after it do not run on this scan. Each of them keeps its state.
Example
with Program(): with rung(Hold): end_early()
fill
Fill instruction.
Writes a constant value to every element in a BlockRange.
Example
with rung(ClearEnable): fill(0, DS.select(1, 100)) fill(0xF, Txt.select(1, 4), hex=True) # "F" in each, as CLICK's fill(Fh, ...)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Value to write (literal, Tag, or Expression). |
required |
dest
|
Any
|
Dest BlockRange or IndirectBlockRange from .select(). |
required |
oneshot
|
bool
|
If True, execute only once per rung activation. |
False
|
hex
|
bool | int
|
If True, the value is one hex digit (0 to 0xF, but not 0xE), and each
Char gets that digit. |
False
|
latch
Latch/Set instruction (SET).
Sets target to True. Unlike OUT, does NOT reset when rung goes false. Use reset() to turn off.
Example
with rung(StartButton): latch(MotorRunning) latch(C.select(1, 8))
out
out(
target: Tag | BlockRange | ImmediateRef,
*,
oneshot: bool = False,
) -> Tag | BlockRange | ImmediateRef
Output coil instruction (OUT).
Sets target to True when rung is true. Resets to False when rung goes false.
Example
with rung(Button): out(Light) out(Y.select(1, 4))
pack_bits
Pack BOOL tags from a BlockRange into a register destination.
pack_text
pack_text(
source_range: Any,
dest: Any,
*,
allow_whitespace: bool = False,
oneshot: bool = False,
) -> None
Pack Copy text mode: parse a TXT/CHAR range into a numeric destination.
pack_words
Pack two 16-bit tags from a BlockRange into a 32-bit destination.
reset
Reset/Unlatch instruction (RST).
Clears targets to their type's OFF/zero value, independent of their initialization default.
Example
with rung(StopButton): reset(MotorRunning) reset(C.select(1, 8))
return_early
Return from the current subroutine.
Example
with subroutine("my_sub"): with rung(Abort): return_early()
run_enabled_function
run_enabled_function(
fn: Callable[..., dict[str, Any]],
*,
ins: dict[
str, Tag | IndirectRef | IndirectExprRef | Any
]
| None = None,
outs: dict[str, Tag | IndirectRef | IndirectExprRef]
| None = None,
) -> None
Execute a synchronous function every scan with rung enabled state.
run_function
run_function(
fn: Callable[..., dict[str, Any]],
*,
ins: dict[
str, Tag | IndirectRef | IndirectExprRef | Any
]
| None = None,
outs: dict[str, Tag | IndirectRef | IndirectExprRef]
| None = None,
oneshot: bool = False,
) -> None
Execute a synchronous function when rung power is true.
search
search(
comparison: RangeComparison,
*,
result: Tag,
found: Tag,
continuous: bool = False,
oneshot: bool = False,
) -> Tag
Search instruction.
Scans a selected range and writes the first matching address into result.
Writes found True on hit; on miss writes result=-1 and found=False.
The first argument is a comparison expression built from a .select() range::
search(DS.select(1, 100) >= 100, result=FoundAddr, found=FoundFlag)
search(Txt.select(1, 50) == "A", result=FoundAddr, found=FoundFlag)
unpack_to_bits
Unpack a register source into BOOL tags in a BlockRange.
pyrung.PyrungNameError
Bases: ValueError
Tag/Block name could not be inferred and none was provided.
pyrung.PyrungNameWarning
Bases: UserWarning
Explicit tag name doesn't match the inferred variable name.
pyrung.branch
Create a parallel branch within a rung.
A branch executes when both the parent rung conditions AND the branch's own conditions are true.
Example
with rung(Step == 0): out(Light1) with branch(AutoMode): # Only executes if Step==0 AND AutoMode out(Light2) copy(1, Step, oneshot=True)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conditions
|
ConditionTerm
|
Conditions that must be true (in addition to parent rung) for this branch's instructions to execute. |
()
|
Returns:
| Type | Description |
|---|---|
Branch
|
Branch context manager. |
pyrung.comment
Attach a comment to the next rung.
The comment is consumed by the immediately following rung() constructor.
Must be called inside a Program context.
Example::
comment("UnitMode Change")
with rung(C_UnitModeChgRequest):
copy(1, C_UnitModeChgRequestBool, oneshot=True)
pyrung.forloop
Create a repeated block context.
A bare instruction in the body is an always-true body rung. A body rung
with contacts is written as with rung(...) inside the loop. Its
contacts are evaluated on every iteration. Loops nest up to three deep,
each with its own loop.idx.
As on CLICK, a false loop rung skips the body. Its coils hold and its
one-shots do not re-arm. A tag count is read once. An Int is read as
unsigned 16-bit, so -1 runs 65535 iterations. A Dint is read whole and
signed, so 65536 runs 65536 iterations, and 0 or below runs none. A
constant is read whole, so forloop(70000) runs 70000.
Example
with rung(Enable): with forloop(10) as loop: copy(Source[loop.idx + 1], Dest[loop.idx + 1]) with rung(Fault): break_loop()
pyrung.break_loop
Leave the innermost forloop now; the scan continues after the loop.
Must sit in a body rung with a contact (CLICK Break).
Example
with rung(Enable): with forloop(10) as loop: with rung(Fault): break_loop()
pyrung.continue_loop
Skip the rest of this forloop iteration and start the next one.
Must sit in a body rung with a contact (CLICK Continue).
Example
with rung(Enable): with forloop(10) as loop: with rung(Src[loop.idx] == 0): continue_loop() copy(Src[loop.idx], Dst[loop.idx])
pyrung.subroutine
Define a named subroutine.
Subroutines are only executed when called via call(). They are NOT executed during normal program scan.
Example
with Program() as logic: with rung(Button): call("my_sub")
with subroutine("my_sub"):
with rung():
out(Light)