Skip to content

Click Dialect API

Tier: Dialect Surface

Click prebuilt blocks, aliases, and validation/communication helpers.

Mapping and Runtime Helpers

MIGRATIONS module-attribute

MIGRATIONS: tuple[CommentMigration, ...] = (
    CommentMigration(
        1,
        "profile=pulse:on_dwell=..|off_dwell=.. -> flasher_on=.., flasher_off=..",
        "pulse",
        (
            ("on_dwell", "flasher_on"),
            ("off_dwell", "flasher_off"),
        ),
        ("on_dwell", "off_dwell"),
    ),
    CommentMigration(
        2,
        "profile=ramp:up=..|down=.. -> ramp_on=.., ramp_off=..",
        "ramp",
        (("up", "ramp_on"), ("down", "ramp_off")),
        ("up",),
    ),
    CommentMigration(
        3,
        "profile=approach:toward=..|rate=.. -> approach_to=.., approach_rate=..",
        "approach",
        (
            ("toward", "approach_to"),
            ("rate", "approach_rate"),
        ),
        ("toward", "rate"),
    ),
)

Formula module-attribute

Formula: TypeAlias = (
    Number
    | Address
    | Pointer
    | Pi
    | Call
    | RangeCall
    | Negate
    | Plus
    | BinaryOp
)

ValidationMode module-attribute

ValidationMode = Literal['warn', 'strict']

CLICK_STEP_LIMIT module-attribute

CLICK_STEP_LIMIT = 8000

TagMap

Parameters:

Name Type Description Default
mappings dict[Tag | Block, Tag | BlockRange] | Iterable[MappingEntry] | None

dict[Tag | Block, Tag | BlockRange], Iterable[MappingEntry], or None for an empty map.

None
include_system bool

Whether to include built-in system tag mappings (SC/SD points). Default True.

True
from_nickname_file classmethod
from_nickname_file(
    path: str | Path,
    *,
    mode: Literal["warn", "strict"] = "warn",
) -> TagMap
to_nickname_file
to_nickname_file(
    path: str | Path, *, blocks: Iterable[Any] | None = None
) -> int
resolve
resolve(
    source: Tag | Block | str, index: int | None = None
) -> str
validate
validate(
    program: Program,
    mode: ValidationMode = "warn",
    profile: HardwareProfile | None = None,
) -> ClickValidationReport

Parameters:

Name Type Description Default
program Program

The Program to validate.

required
mode ValidationMode

"warn" (findings as hints) or "strict" (findings as errors).

'warn'
profile HardwareProfile | None

Optional hardware capability profile override.

None

Returns:

Type Description
ClickValidationReport

ClickValidationReport with categorized findings.

mapped_slots
mapped_slots() -> tuple[MappedSlot, ...]
tags_from_plc_data
tags_from_plc_data(
    data: Mapping[str, bool | int | float | str],
    *,
    blocks: Iterable[Any] | None = None,
) -> dict[str, bool | int | float | str]

Parameters:

Name Type Description Default
data Mapping[str, bool | int | float | str]

{hardware_address: value} dict — keys are normalised Click display addresses such as "X001" or "DS3".

required
blocks Iterable[Any] | None

Click bank blocks whose slots the program uses directly, without a TagMap entry (x.slot(1, name="Button") or a bare ds[5]). Accepts a ClickBlockSet or any iterable of blocks; non-Block items are silently skipped. When omitted, only addresses mapped by this TagMap are returned.

None

Returns:

Type Description
dict[str, bool | int | float | str]

{logical_name: value} dict containing only the addresses

dict[str, bool | int | float | str]

that appear in both data and this TagMap (or blocks).

load_snapshot
load_snapshot(
    path: str | Path,
    *,
    skip_default: bool = True,
    blocks: Iterable[Any] | None = None,
) -> SystemState

Parameters:

Name Type Description Default
path str | Path

Path to a CSV file exported via Click Programming Software's PLC → Read Data from PLC → All → Save.

required
skip_default bool

If True (default), omit addresses that still hold their power-on default.

True
blocks Iterable[Any] | None

Click bank blocks to seed for slots used without a TagMap entry; see :meth:tags_from_plc_data. Generated projects export this as blocks beside mapping.

None

Returns:

Name Type Description
A SystemState

class:SystemState seeded with the mapped tag values.

Warns:

Type Description
SkippedAddressesWarning

If some TXT addresses can be read more than one way. CLICK writes a TXT comma without quotes, so a TXT row that holds a comma and an empty address can be read more than one way. load_snapshot leaves those addresses out of the state and loads the rest of the file. The warning's addresses attribute lists the skipped addresses. To refuse such a file, turn the warning into an error with :mod:warnings.

Raises:

Type Description
ValueError

If the file is not a readable PLC data dump. The message keeps the reader's detail, such as the row that is malformed.

SystemNicknameRepair dataclass

SystemNicknameRepairRequired

Bases: ValueError

TagMeta dataclass

physical_kind property
physical_kind: PhysicalKind | None
physical_values
physical_values() -> dict[str, str | bool]

OldCommentFormError

Bases: ValueError

SkippedAddressesWarning

Bases: UserWarning

LadderBundle dataclass

LadderExportError

Bases: RuntimeError

CodegenIdentityError

Bases: Exception

ClickDataProvider

Parameters:

Name Type Description Default
runner PLC | Callable[[], PLC]

The active PLC whose state is served, or a zero-argument callable returning it. Pass a callable when the runner can be replaced while the provider is in use (a debug session reload).

required
tag_map TagMap

Mapping from logical tag names to Click hardware addresses.

required
fallback DataProvider | None

Optional provider for unmapped addresses. Defaults to an in-memory provider.

None
blocks Iterable[Any] | None

Click bank blocks whose slots the program uses directly, without a TagMap entry (x.slot(1, name="Start") or a bare ds[5]). Accepts a ClickBlockSet or any iterable of blocks. The provider uses the blocks of X, Y, C, T, CT, DS, DD, DH, DF and TXT.

None
on_stop Callable[[], None] | None

Called instead of runner.stop() when a write to the STOP command bit (SC50) reaches the provider. pyclickplc's Modbus server refuses that write (exception code 2), so a Modbus client never gets here.

None
tag_name
tag_name(address: str) -> str | None

Raises:

Type Description
ValueError

If address is not a valid Click address.

ModbusAddress dataclass

ModbusReceiveInstruction dataclass

Bases: Instruction

external_payload_names property
external_payload_names: frozenset[str]

ModbusRtuTarget dataclass

Bases: _TargetEquality

ModbusSendInstruction dataclass

Bases: Instruction

ModbusTcpTarget dataclass

Bases: _TargetEquality

RegisterType

Bases: Enum

WordOrder

Bases: Enum

NopInstruction

Bases: Instruction

execute
execute(ctx: ScanContext, enabled: bool) -> None
is_terminal
is_terminal() -> bool

RawInstruction

Bases: Instruction

execute
execute(ctx: ScanContext, enabled: bool) -> None

UndecodedInstruction

Bases: Instruction

error property
error: str
rung property
rung: int
row property
row: int | None
column property
column: int | None
stop property
stop: UndecodedStop
execute
execute(ctx: ScanContext, enabled: bool) -> None
is_terminal
is_terminal() -> bool
reason
reason(at: str | None = None) -> str
effect
effect() -> str

ClickValidationReport dataclass

ClickFinding dataclass

Bases: _FindingTextMixin

StepEstimate dataclass

format_tag_meta

format_tag_meta(meta: TagMeta | None) -> str

parse_tag_meta

parse_tag_meta(comment: str) -> tuple[TagMeta | None, str]

comment_needs_upgrade

comment_needs_upgrade(comment: str) -> bool

old_form_tokens

old_form_tokens(comment: str) -> tuple[str, ...]

upgrade_comment

upgrade_comment(comment: str) -> str

ladder_to_pyrung

ladder_to_pyrung(
    source: str | Path | LadderBundle,
    *,
    nickname_csv: str | Path | None = None,
    nicknames: dict[str, str] | None = None,
    analog_inputs: Iterable[str] = (),
    output_path: str | Path | None = None,
    validate: bool = True,
) -> str

Parameters:

Name Type Description Default
source str | Path | LadderBundle

A file path (to main.csv or a directory containing main.csv and optional subroutines/*.csv files), or a :class:LadderBundle for in-memory round-trip without disk I/O.

required
nickname_csv str | Path | None

Optional path to a Click nickname CSV file (Address.csv). Read via pyclickplc.read_csv(), extracts {display_address: nickname} pairs for variable name substitution.

None
nicknames dict[str, str] | None

Optional pre-parsed {operand: nickname} dict. Alternative to nickname_csv; useful when the caller already has the map.

None
analog_inputs Iterable[str]

Analog input DF addresses supplied by project channel parameters; their generated tags are marked external.

()
output_path str | Path | None

Optional path to write the generated Python file. If None, the code is returned as a string only.

None
validate bool

When True (default), run three codegen self-checks. A settings check confirms that the declarations give each address the Retentive setting and initial value of its nickname CSV row (it raises :class:CodegenIdentityError). A rung-analysis check confirms that no source contact is silently dropped for lack of wiring into an output. A logic check confirms that every output in the generated code keeps the condition (each contact from its own cell), pins, CLICK rung and wire that the source rows give it. The last two raise ValueError. When False, a dropped contact only warns and the logic check is skipped.

True

Returns:

Type Description
str

The generated Python source code as a string.

Raises:

Type Description
ValueError

If both nickname_csv and nicknames are provided, if required subroutine CSV files are missing, if the CSV format is invalid, or if validate is True and a rung drops a source contact (one that reaches no output, or one the generated code would leave out).

TypeError

If source is not a supported type.

CodegenIdentityError

If validate is True and the generated code would not give an address the settings of its nickname CSV row.

ladder_to_pyrung_project

ladder_to_pyrung_project(
    source: str | Path | LadderBundle,
    *,
    nickname_csv: str | Path | None = None,
    nicknames: dict[str, str] | None = None,
    analog_inputs: Iterable[str] = (),
    output_dir: str | Path | None = None,
    index: bool = False,
    overwrite: bool = False,
    machine_name: str = "PLC",
    validate: bool = True,
    host_guides: Sequence[str] = (),
) -> dict[str, str]

Parameters:

Name Type Description Default
source str | Path | LadderBundle

A file path (to main.csv or a directory containing main.csv and optional subroutines/*.csv files), or a :class:LadderBundle for in-memory round-trip without disk I/O.

required
nickname_csv str | Path | None

Optional path to a Click nickname CSV file (Address.csv).

None
nicknames dict[str, str] | None

Optional pre-parsed {operand: nickname} dict.

None
analog_inputs Iterable[str]

Analog input DF addresses supplied by project channel parameters; their generated tags are marked external.

()
output_dir str | Path | None

Optional directory to write the project files into. If None, files are returned as strings only.

None
overwrite bool

When False (default), scaffolding files (pyproject.toml, README.md, .vscode/) are skipped if they already exist on disk. In an existing README.md, AGENTS.md or CLAUDE.md, pyrung rewrites only the line that holds <!-- pyrung:guidance -->. A file without that marker stays as it is, except a CLAUDE.md that holds only @AGENTS.md. pyrung wrote that file before the marker existed, so pyrung adds the marked line to it. Logic files under src/plc/ and click-cheatsheet.md are always written.

False
machine_name str

Human-readable machine name for AGENTS.md header (e.g. from the .ckp filename).

'PLC'
validate bool

When True (default), run codegen self-checks (see :func:ladder_to_pyrung): a check of each address's settings (raises :class:CodegenIdentityError), a dropped-contact check and a generated-logic check (both raise ValueError). When False, dropped contacts only warn.

True
host_guides Sequence[str]

File names of the guides that the tool building the project writes itself, such as ["AGENTS.mytool.md", "README.mytool.md"]. Each name is a bare file name in output_dir of the form AGENTS.<name>.md or README.<name>.md. pyrung links each AGENTS file from AGENTS.md, AGENTS.pyrung.md and CLAUDE.md, and each README file from README.md and README.pyrung.md. With an AGENTS file, AGENTS.pyrung.md leaves out how to start a session and how to get changes into CLICK. With a README file, README.pyrung.md leaves out its link on how to get changes into CLICK. The tool's guides say that. pyrung never reads, writes or deletes these files, so they need not exist yet. Raises ValueError for a path, a name of another form, a pyrung name, or a name listed twice.

()

Returns:

Type Description
dict[str, str]

A dict mapping relative file paths to their content, e.g.

dict[str, str]

{"src/plc/main.py": "...", "src/plc/tags.py": "..."}.

parse_click_formula

parse_click_formula(
    text: str, *, hex_mode: bool = False
) -> Formula | None

pyrung_to_ladder

pyrung_to_ladder(
    program: Program,
    tag_map: TagMap,
    *,
    index: bool = False,
    validate: bool = True,
    allow: Collection[str] = (),
) -> LadderBundle

Parameters:

Name Type Description Default
program Program

The Program to export.

required
tag_map TagMap

TagMap mapping logical tags to Click hardware addresses.

required
index bool

When True, number rung markers sequentially (R1, R2, ...) instead of bare R. Counter restarts per program scope.

False
validate bool

When True (default), run pre-export checks and round-trip verification. The rows must analyze back to the program's outputs. Importing them (ladder_to_pyrung) must keep each output's condition, pins and CLICK rung. Set to False to skip validation for speed.

True
allow Collection[str]

Finding codes that the precheck lets through, for an export that knowingly carries what the CLICK editor refuses (the conformance suite's paste probes). The precheck still refuses the export for other findings.

()

Returns:

Type Description
LadderBundle

A LadderBundle containing main and subroutine row matrices.

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

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

undecoded_rungs

undecoded_rungs(
    program: Program,
) -> Iterator[tuple[str | None, int, UndecodedInstruction]]

undecoded_notice

undecoded_notice(program: Program) -> str

estimate_steps

estimate_steps(bundle: LadderBundle) -> StepEstimate

Prebuilt Blocks and Aliases

Bit module-attribute
Bit = Bool
Int2 module-attribute
Int2 = Dint
Float module-attribute
Float = Real
Hex module-attribute
Hex = Word
Txt module-attribute
Txt = Char
ClickBlockSet

Bases: NamedTuple

ClickBlocks
ClickBlocks() -> ClickBlockSet