Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

S7 link (s7)

The s7 link reads and writes Siemens S7-300, S7-400, S7-1200 and S7-1500 PLCs over S7comm on ISO-on-TCP (TCP port 102). It uses absolute addresses (DB10.DBW6, MW20, IB0, …), not the symbols of a TIA Portal project. It runs on the driver framework (ADR 0004), so the tree, the add_* / edit / remove / restart / stop / start actions, the states, polling, read-back writes and the quality ladder work as in the other framework links (see links.md).

The protocol codec is part of the crate (links/s7/src/proto.rs): TPKT (RFC 1006), COTP class 0 (ISO 8073), and the S7 PDUs Setup Communication, Read Var, Write Var and the SZL read. The link uses no third-party S7 library.

Prepare the PLC

  • S7-1200 / S7-1500: in the CPU properties, Protection & Security → Connection mechanisms, turn on Permit access with PUT/GET communication from remote partner. Without it, the CPU answers every read and write with error 0x8104, and the link reports PLC error 0x8104: this service is not implemented on the module … enable "Permit access with PUT/GET communication".
  • Data blocks on S7-1200 / S7-1500: absolute addressing needs a non-optimized DB. In the DB properties, turn off Optimized block access, then compile and download again. An optimized DB answers item error 0x05 (address out of range) or 0x03 (access not allowed), and the link shows the code and this hint.
  • S7-300 / S7-400: no settings are needed. A protection level that needs a password blocks writes; this link cannot send the password (see Limits).

Tree

<link>/
  <connection>/          one PLC (Add Connection)
    status, error        framework leaves
    requests, errors, timeouts, exceptions, late_replies, last_rtt_ms, avg_rtt_ms
    <device>/            one CPU (Add Device)
      status, error, diagnostics leaves as on the connection
      <folder>/…         optional folders (add_folder)
      <point>            one value (Add Point)

A connection is one TCP connection to one CPU (rack and slot). A device is the CPU on that connection. Normally a connection has one device. More devices on one connection read the same CPU; you can use them to group points with different device settings (ping, batching, clock offset).

Connection parameters

ParamDisplayDefaultBoundsMeaning
hostHost(required)IP address or host name of the PLC or its CP
portPort1020…65535ISO-on-TCP port
rackRack00…7rack of the CPU
slotSlot10…31slot of the CPU: 1 for S7-1200/1500, 2 for S7-300, as configured for S7-400
conn_typeConnection Typepgpg, op, s7_basicconnection resource of the remote TSAP (PG 0x01, OP 0x02, S7 basic 0x03)
timeout_msTimeout (ms)2000100…10000bound on each request and on each step of connecting
pdu_sizePDU Size480240…960the PDU size the link asks for; the PLC can agree on less

The remote TSAP is conn_type << 8 | rack * 32 + slot (rack 0, slot 1, PG: 0x0101). The local TSAP is 0x0100. The link cannot set other TSAPs.

The PLC agrees on the PDU size in Setup Communication. Typical values are 240 (S7-300, S7-1200) and 480 or 960 (S7-400, S7-1500). The connection action Connection Info (connection_info) shows the agreed size; see Actions. The link refuses a PLC that agrees on less than 96 bytes.

Device parameters

ParamDisplayDefaultBoundsMeaning
pingPingszlszl, read, noneszl: read SZL 0x0011 (module identification); read: read 1 byte at ping_address; none: no ping
ping_addressPing AddressMB0an addressthe byte that ping = read reads
ping_sPing Rate (s)50.1…3600time between pings
max_gapMax Gap (bytes)40…256points of one area and DB at most this many bytes apart are read as one item; 0 = only touching ones
max_itemsMax Items per Read201…20items in one Read Var request
tz_offset_minPLC Clock Offset (min)0−720…840the offset of the PLC clock from UTC, for DATE_AND_TIME values
republish_sRepublish Unchanged Values (s)00…3600publish an unchanged value again after this time; 0 = only on a change

Any answer to a ping means that the CPU is alive, an error answer too (for example a CPU without the SZL list). Only no answer counts as a miss.

Point parameters

ParamDisplayDefaultBoundsMeaning
addressAddress(required)see belowwhere the value is
dtypeData Typeautosee belowthe data type
poll_sPoll Rate (s)10.01…86400time between reads
scaleScaling1not 0published = raw × scale + offset (numbers only)
offsetScaling Offset0
writableWritablefalsethe point takes ~set (not on inputs, timers and counters)
unitUnit“”shown in ~meta.unit

The link checks the address and the data type when you add or edit a point. An error tells what is wrong, for example address "DB10.DBX4": a bit address needs a bit number (X4.3, M1.0) or dtype: REAL takes 4 bytes; use a D address (DBD, MD).

Addresses

Siemens notation; case and spaces do not matter.

AreaBitByteWordDouble word
Data blockDB10.DBX4.3DB10.DBB5DB10.DBW6DB10.DBD8
Bit memoryM1.0, MX1.0MB1MW20MD24
Inputs (I or E)I0.1, IX0.1, E0.1IB0IW2ID4
Outputs (Q or A)Q1.0, QX1.0, A1.0QB1QW2QD4
TimersT5
Counters (C or Z)C3, Z3

The DB number is 1…65535. The byte offset is 0…2097151 (the limit of the S7 address field). A timer or counter number is 0…65535.

An address can carry its type after a colon: DB10.DBD8:REAL, DB1.DBW0:INT, DB1.DBB20:STRING[16], DB1.DBB30:DT, C3:COUNTER.

Data types

The type comes from the :TYPE suffix, else from dtype, else from the width letter: X → BOOL, B → BYTE, W → WORD, D → DWORD, T → S5TIME, C → WORD. If the suffix and dtype are both set, they must be the same type.

dtypeSuffixBytesWidthPublished as
boolBOOL1 bitXbool
byteBYTE1Bnumber 0…255
wordWORD2W, B, T, Cnumber 0…65535
dwordDWORD4D, Bnumber 0…4294967295
intINT2W, Bnumber −32768…32767
dintDINT4D, Bnumber
realREAL4D, Bnumber (the shortest decimal of the float: 0.1, not 0.10000000149)
lrealLREAL8Bnumber
stringSTRING[n], STRINGn + 2Btext; STRING without a length is STRING[254] and reads 256 bytes: a short string near the end of a DB then fails with item error 0x05, so give the real length
s5timeS5TIME2W, B, Tseconds (number)
timeTIME4D, Bseconds (number; TIME is DINT milliseconds)
date_and_timeDATE_AND_TIME, DT8BRFC 3339 text
counterCOUNTER2Cnumber 0…999 (3 BCD digits)

Conversions:

  • All values are big-endian, as the PLC stores them.
  • BOOL is one bit of a byte (.0 … .7).
  • STRING[n]: byte 0 is the maximum length, byte 1 the actual length, then the characters, one byte each. The link reads them as Latin-1. An actual length above the maximum is an error. If n is less than the PLC’s maximum, the text is cut to n characters.
  • S5TIME: bits 12–13 are the time base (10 ms, 100 ms, 1 s, 10 s), bits 0–11 three BCD digits. Range 0…9990 s. A write picks the finest time base that holds the value and rounds to it (12.34 s → 12.3 s).
  • TIME: signed milliseconds, published in seconds.
  • DATE_AND_TIME: 8 BCD bytes (year 1990…2089, month, day, hour, minute, second, milliseconds, weekday). The PLC clock has no time zone; the link writes it with the device’s tz_offset_min (Z for 0, else +02:00 and so on). A write takes any RFC 3339 time (Z or an offset, T or a space between date and time) and converts it to the PLC’s zone. The link computes the weekday.
  • Timers (T5): an S5TIME value in seconds, or with dtype = word the raw timer word.
  • Counters (C3): with dtype = word (the default) the raw counter word; with C3:COUNTER the word read as 3 BCD digits. Not verified on hardware: S7 documentation says the counter value is BCD in some places and binary in others. Use word and compare with the PLC before you use counter.
  • scale and offset apply to number types only. An unscaled integer is published as an integer, a scaled one as a float.

Reads

The framework polls each group of points with the same device and poll rate. The link:

  1. merges the points of one area and DB into spans when they are at most max_gap bytes apart (timers and counters: max_gap / 2 numbers);
  2. cuts a span that is longer than one reply item into several items (a reply item carries at most PDU − 18 bytes);
  3. packs the items into Read Var requests. A request carries at most max_items items, and both the request (12 + 12 × items bytes) and the reply (14 + Σ (4 + item bytes, rounded up to even)) must fit the agreed PDU.

The plan is kept until the group changes or the PDU size changes.

Each item has its own return code. An error code fails only the points of that item. If a merged item fails, the link reads its points again, each one alone, in the same poll. Only the points that fail alone get the error. A point that fails alone while a neighbour of the same item reads is read alone from then on (until the group changes). So one bad address does not fail its neighbours. When all points of the item fail alone too (for example a DB that is missing for a moment during a download), there is nothing to isolate: the item stays merged and is read as one again when the DB answers. A header error (the PLC refuses the whole request, for example PUT/GET off) fails all points of that request alike; the link does not read them one by one, and merging stays as it is.

Writes

A write is one Write Var request for the point. There is no optimistic update: the framework reads the point back and publishes what the PLC holds.

  • BOOL: the bit transport size, one bit. The other bits of the byte do not change, and there is no read-modify-write of the byte.
  • STRING: the link writes the actual-length byte and the characters, from the second byte on. It never writes the maximum-length byte, so the PLC’s declared length stays. A text longer than n, or with characters outside Latin-1, is refused. The PLC does not stop a byte write at the string’s end, so the link first reads the maximum-length byte and refuses a text longer than the PLC’s declared length (text of 15 characters does not fit the PLC's STRING[10]); nothing is written then. A write is bounded by the PLC’s length, whatever n says.
  • A value longer than one request (a long STRING on a small PDU) goes in parts of at most PDU − 28 bytes, the last part first. A STRING’s actual-length byte is in the first part, so it goes last: if a part fails, the PLC keeps the old length, and the old text stays valid up to it. The error says how many parts went out, and the read-back shows what the PLC holds.
  • A value out of range for its type is refused (invalid_parameter), and nothing is sent.
  • Points on inputs (I), timers and counters cannot be writable. A point that is not writable refuses ~set.

Errors and quality

What happensError classResult
I/O error, closed socket, COTP disconnect, garbled frametransportthe connection goes to failed with its error leaf; its devices go to stopped_by_parent; the framework reconnects with backoff (1 s … 60 s)
no reply within timeout_msdevicethe points of that request and of the requests after it in the poll (not sent) go to uncertain/stale, after 3 misses in a row to bad/comm_fail; the last value stays. If other requests of the poll were answered, the device stays connected; if none was, the device takes the same ladder
header error in the reply (PLC error 0x…)pointthe points of that request are bad; the device stays connected
item return code (PLC item error 0x…)pointthat point only is bad

Item return codes: 0x01 hardware fault, 0x03 access not allowed, 0x05 address out of range, 0x06 data type not supported, 0x07 data type inconsistent, 0x0A object does not exist (no such DB). Write replies and the read actions return the text of the code.

Each request carries a PDU reference. A reply that comes after its timeout has the reference of an earlier request; the link drops it and counts it in late_replies. It is never taken for a later request. A request cut while it was being sent leaves the TCP stream in an unknown state; the next request then reports a transport error and the link reconnects.

Diagnostics (on the connection and on each device): requests, errors (I/O or protocol errors), timeouts, exceptions (replies with a header error or a failed item), late_replies, last_rtt_ms, avg_rtt_ms.

Actions

Driver actions run on the connection’s owner task, between polls. They need the connection to be connected. read_szl and read_address send a request and hold the connection while they wait (polls of the connection wait too), so they are commissioning actions at level config.

NodeActionLevelArgumentsResult
connectionconnection_info (Connection Info)read{pdu_size, max_amq_calling, max_amq_called, local_tsap, remote_tsap, late_replies}
deviceread_szl (Read SZL)configid (number), index (number, 0){id, index, record_length, records, more}, and order_code for SZL 0x0011
deviceread_address (Read Address)configaddress, dtype (optional){value, dtype}, unscaled

read_szl reads the first part of an SZL list only (more = true if the PLC has more parts). read_address reads any address once, without adding a point; use it to check an address or the PUT/GET setting.

Simulator

wyrm-s7-sim is an S7 server for tests and demos (feature bin). It answers COTP connect, Setup Communication, Read Var, Write Var and SZL 0x0011 over DB1 (1000 bytes), DB2 (100 bytes), M, I and Q (1024 bytes each), and 256 timers and counters.

cargo run -p wyrm-link-s7 --features bin --bin wyrm-s7-sim -- --listen 127.0.0.1:10102
cargo run -p wyrm-link-s7 --features bin --bin wyrm-s7-sim -- --pdu 240   # a small PDU

In the demo values, DB1.DBW0 (INT) counts up once per second, DB1.DBD2:REAL is 21.5, DB1.DBX6.0 toggles, DB1.DBB8:STRING[16] is “WYRM” and MW10 is 1234. Then add a link with driver s7 and this tree:

{
  connections: {
    plc1: {
      host: "127.0.0.1", port: 10102, rack: 0, slot: 1,
      devices: {
        cpu: {
          points: {
            counter: { address: "DB1.DBW0:INT", poll_s: 1 },
            temp:    { address: "DB1.DBD2:REAL", unit: "°C" },
            name:    { address: "DB1.DBB8:STRING[16]" },
            mw:      { address: "MW10", writable: true },
          },
        },
      },
    },
  },
}

The tests (links/s7/tests/sim.rs) use the simulator in process (wyrm_link_s7::sim, feature sim) with its failure modes: an address out of range (item error 0x05, a missing DB 0x0A), a small PDU (a request or reply that does not fit is answered with header error 0x8500 and counted), silence, one late reply, closing the connection, PUT/GET refused (0x8104) and no SZL (0xD401).

Limits

What S7 PLCs have that this link does not do:

  • S7comm-plus (the protected protocol of S7-1200 from firmware 4 and of S7-1500) and symbolic access: optimized DBs and tag names cannot be read. Use non-optimized DBs and PUT/GET, or the OPC UA server of the CPU.
  • Protection-level password of S7-300/400 (userdata function group 5): a CPU that needs a password for writes refuses them.
  • Other TSAPs: the local TSAP is always 0x0100 and the remote TSAP comes from rack, slot and connection type. LOGO! and S7-200 with their own TSAPs are not supported.
  • Routing through a CP to another subnet, and several CPUs on one connection.
  • Writes to inputs, timers and counters; peripheral areas (PI, PQ), V memory (S7-200), WSTRING, DTL, DATE, TIME_OF_DAY, CHAR as its own type.
  • Program upload or download, block info, PLC run/stop, alarms and cyclic data (userdata push functions).
  • More SZL parts after the first in read_szl.
  • A status leaf with the agreed PDU size: the framework has no hook for a driver leaf on a connection, so the size is in connection_info.
  • The link is tested against its simulator only. It has not been checked against a real CPU yet; the counter encoding in particular is not verified.