Instruction Set API
Tier: Stable Core
Instruction blocks, conditions, and copy/casting modifiers.
pyrung.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))
pyrung.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))
pyrung.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))
pyrung.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)
pyrung.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.
pyrung.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.
pyrung.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
|
pyrung.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
|
pyrung.pack_bits
Pack BOOL tags from a BlockRange into a register destination.
pyrung.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.
pyrung.pack_words
Pack two 16-bit tags from a BlockRange into a 32-bit destination.
pyrung.unpack_to_bits
Unpack a register source into BOOL tags in a BlockRange.
pyrung.unpack_to_words
Unpack a 32-bit register source into two 16-bit tags in a BlockRange.
pyrung.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.
pyrung.calc
Deprecated. Use math(), CLICK's name for the Math instruction.
pyrung.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)
pyrung.return_early
Return from the current subroutine.
Example
with subroutine("my_sub"): with rung(Abort): return_early()
pyrung.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()
pyrung.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(). |
pyrung.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(). |
pyrung.event_drum
event_drum(
*,
outputs: Sequence[Tag],
events: Sequence[Condition | Tag],
pattern: Sequence[Sequence[bool | int]],
current_step: Tag,
completion_flag: Tag,
) -> EventDrumBuilder
pyrung.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)
pyrung.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)
pyrung.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. |
pyrung.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. |
pyrung.time_drum
time_drum(
*,
outputs: Sequence[Tag],
presets: Sequence[Tag | int],
unit: TimeUnitStr = "ms",
pattern: Sequence[Sequence[bool | int]],
current_step: Tag,
accumulator: Tag,
completion_flag: Tag,
) -> TimeDrumBuilder
pyrung.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.
pyrung.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)
pyrung.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'
|
pyrung.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'
|
pyrung.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
|
pyrung.send
send(
*,
target: str | ModbusTcpTarget | ModbusRtuTarget,
remote_start: str | ModbusAddress,
source: Tag | BlockRange,
sending: Tag | None = None,
success: Tag | None = None,
error: Tag | None = None,
exception_response: Tag | None = None,
count: int | None = None,
word_swap: bool = False,
) -> None
Modbus send instruction (write local values to a remote device).
target may be a :class:ModbusTcpTarget or :class:ModbusRtuTarget
(live simulation) or a plain string name (codegen placeholder).
remote_start may be a Click address string (e.g. "DS1") for Click
PLCs, or a :class:ModbusAddress for raw Modbus devices.
Status bits are optional, as in CLICK. If you leave a status bit off, the instruction still writes that bit, to a hidden tag. CLICK export leaves the hidden tag off.
pyrung.receive
receive(
*,
target: str | ModbusTcpTarget | ModbusRtuTarget,
remote_start: str | ModbusAddress,
dest: Tag | BlockRange,
receiving: Tag | None = None,
success: Tag | None = None,
error: Tag | None = None,
exception_response: Tag | None = None,
count: int | None = None,
word_swap: bool = False,
) -> None
Modbus receive instruction (read remote device values into local tags).
target may be a :class:ModbusTcpTarget or :class:ModbusRtuTarget
(live simulation) or a plain string name (codegen placeholder).
remote_start may be a Click address string (e.g. "DS1") for Click
PLCs, or a :class:ModbusAddress for raw Modbus devices.
Status bits are optional, as in CLICK. If you leave a status bit off, the instruction still writes that bit, to a hidden tag. CLICK export leaves the hidden tag off.
pyrung.ModbusAddress
dataclass
Modbus register address.
address accepts:
- MODBUS 984
int— e.g.400001(prefix encodes register type) - MODBUS Hex
strwithhsuffix — e.g."0h","FFFEh" - Raw
int0–0xFFFE — low-level register offset
notation records which form was written, so CLICK export can keep it.
It takes no part in equality: "64h" and 400101 are the same register.
pyrung.ModbusRtuTarget
dataclass
Bases: _TargetEquality
Connection details for a remote Modbus RTU (serial) device.
device_id is a number 0..247 or a DS tag that holds it.
pyrung.ModbusTcpTarget
dataclass
Bases: _TargetEquality
Connection details for a remote Modbus TCP device.
device_id is a number or a DS tag that holds it. com_port is
"ethernet" (the default) or "wlan".
pyrung.RegisterType
Bases: Enum
Modbus register / coil type.
pyrung.WordOrder
Bases: Enum
Word ordering for 32-bit values across register pairs.
pyrung.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
pyrung.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
pyrung.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)
pyrung.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. |
pyrung.immediate
Wrap a tag or block range as an immediate operand.
pyrung.to_value
module-attribute
Text → Numeric conversion using the character's face value.
Corresponds to Click PLC "Copy Character Value" (Option 4b).
Example::
# CHAR '5' → numeric 5
copy(ModeChar, DS[1], convert=to_value)
pyrung.to_ascii
module-attribute
Text → Numeric conversion using the ASCII code.
Corresponds to Click PLC "Copy ASCII Code Value" (Option 4b).
Example::
# CHAR '5' → ASCII 53
copy(ModeChar, DS[1], convert=to_ascii)
pyrung.to_text
to_text(
*,
suppress_zero: bool = True,
exponential: bool = False,
termination_code: int | str | None = None,
hex: bool | int = False,
) -> CopyConverter
Numeric → Text conversion.
Corresponds to the Click PLC Copy Option 4a (Numeric→Text) and Option 4c (Float→Text).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
suppress_zero
|
bool
|
When True (default), leading zeros are omitted (Click PLC "Suppress zero"). When False, leading zeros fill the full digit width of the source data type. A Real source ignores it. |
True
|
exponential
|
bool
|
When True, use scientific notation (Click PLC "Exponential Numbering", Option 4c). Only a Real source takes it. CLICK export refuses it from any other. |
False
|
termination_code
|
int | str | None
|
An ASCII code (int 0–127), single character,
or |
None
|
hex
|
bool | int
|
When True, an integer constant is written in hex, as a
Word is. Corresponds to a hex constant in the CLICK Copy
dialog, such as |
False
|
Examples::
copy(DS[1], Txt[1], convert=to_text())
copy(DS[1], Txt[1], convert=to_text(suppress_zero=False))
copy(DF[1], Txt[1], convert=to_text(exponential=True))
copy(DS[1], Txt[1], convert=to_text(termination_code=0))
copy(DS[1], Txt[1], convert=to_text(termination_code="$0D"))
copy(0xAB, Txt[1], convert=to_text(hex=True))
copy(0xF, Txt[1], convert=to_text(hex=4)) # exports as 000Fh
pyrung.to_binary
module-attribute
Numeric → Text conversion as raw binary.
Corresponds to Click PLC "Copy Binary" (Option 4a). The numeric value is stored directly as an ASCII character.
Example::
# DS1=123 → '{' (ASCII 123)
copy(DS[1], Txt[1], convert=to_binary)
# A CLICK Copy Binary of the hex constant 1Eh
copy(0x1E, Txt[1], convert=to_binary(hex=True))
# A CLICK Copy Binary of 001Eh. The export writes 3 digits.
copy(0x1E, Txt[1], convert=to_binary(hex=3))
# DS1=123 -> '{' in Txt1 and CR in Txt2 (Termination Code $0D)
copy(DS[1], Txt[1], convert=to_binary(termination_code="$0D"))
pyrung.LiteralExpr
Bases: Expression
A constant that math() keeps in its formula, so the operation on it runs at scan time.
Python computes an operation between two numbers when it loads the source, before
pyrung sees the operation. math(5 / 0, DS1) raises ZeroDivisionError then.
math(LiteralExpr(5) / 0, DS1) stores 0 and sets the division-error flag, as a
CLICK does.
pyrung.asin
Arc sine function (returns radians).
pyrung.acos
Arc cosine function (returns radians).
pyrung.atan
Arc tangent function (returns radians).
pyrung.lsh
Left shift function: lsh(value, count).
pyrung.rsh
Right shift function: rsh(value, count).
pyrung.lro
Rotate left function (16-bit): lro(value, count).
pyrung.rro
Rotate right function (16-bit): rro(value, count).
pyrung.randint
Return a random integer from lo to hi inclusive, drawn once per scan.
This is CLICK's RAND. Use it inside math(). Draws are deterministic per scan,
so replay, seek and fork see the same values. In a test, call patch() or
force() on the site's tag (expr.tag) to choose a draw.
A bare Real tag as a bound reads 0 with no flag. Equal bounds, whether constants
or tag values, are a math error. The randint reads 0, the rest of the formula
runs, and a Math sets SC46.
A decimal Math draws over the whole bounds and stores the draw as it stores any
result. Into an Int, a draw outside -32768..32767 wraps and sets SC43. A hex Math
cuts each constant bound to 16 bits, and that draw is its own (expr.ucut_tag).