Reading Siemens PLCs with Python: Resolving CPU refused
The easiest route for reading CPU values is also the route anyone can use to write values and stop the CPU. What needs designing is not the reading code, but the boundaries of what is exposed, to whom, and from where.
1-minute summary
- Symptom / problem
- Reading a Siemens PLC with python-snap7 returns CPU refused.
- Who should read
- Anyone who wants a script or AI to read values from an S7-1200/1500.
- Fix in short
- The machine owner enables PUT/GET and sets up a separate non-optimized export DB. Read only, within an isolated control zone, since PUT/GET has no authentication.
I wanted scripts and AI to read live values from a Siemens PLC to collect trends and count downtime, so I sat down to work through the options. I made two wrong assumptions at the start. First, I thought the engineering API in TIA Portal V15.1, which I already used to edit projects, could also read live tag values. It turns out it cannot. Second, I thought I could start by testing with a simulator. It turns out standard S7-PLCSIM does not listen on TCP 102. The remaining option was to talk directly to the CPU using S7comm through the snap7 library, which requires enabling PUT/GET on the CPU first. That is the part that needs thinking through before doing anything.
Let me be clear about the status first. This material is research and tools I have prepared. I have not tested it against a real PLC for this work. The symptoms and causes below come from notes I collected while researching, not from measurements I took at a machine. If you use this, treat it as a plan that needs to be verified again on your own equipment.
Writing to the memory of a running machine can cause real equipment to move: motors start, valves open, cylinders extend, possibly while someone is standing in front of the machine. That is why I have not included even a single line showing how to write values or issue STOP/RUN commands. The IP address, DB number, and offsets in this article are examples. In actual work, the engineer responsible for that machine must make the decision and enable access themselves.
Openness cannot read live values; the remaining route is S7comm
On the engineering side, I already had a bridge into TIA Portal that could export blocks, import source, and compile (covered in the Openness article). But that API in V15.1 works with the project, not the values running in the CPU. If I want to know the current tank level or whether a motor is running, it cannot answer. I have to ask the CPU.
There are three ways to query the CPU. After working through them, I was left with only one that would definitely work with V15.1-era equipment.
| Reading method | Requirements | Works with V15.1-era equipment |
|---|---|---|
| S7comm through snap7 | PUT/GET enabled, non-optimized DB | Yes, independent of TIA version |
| PLC Web API (JSON-RPC) | S7-1500 FW around 2.8/2.9 or later | Can only be configured in newer TIA versions |
| OPC UA server | S7-1500 FW 2.x requires a license, S7-1200 requires FW 4.4 or later | 1200 requires TIA V16 or later |
TIA V15.1 supports selecting firmware up to V4.3 for S7-1200 and around V2.6 for S7-1500, so the last two options ruled themselves out for the equipment I was interested in. Personally, if the equipment is new enough to support OPC UA, I would choose that first because it provides authentication and lets me assign read permissions. But for older equipment, that leaves snap7, which is both the easiest and the least restrictive route.
Three symptoms and their respective causes
While researching, I recorded the symptoms in a table because the library's error messages do not directly tell you where to fix things. These three symptoms point to completely different places.
| Symptom | Cause noted | Where to look |
|---|---|---|
| Address out of range or CPU refused / function refused | Optimized block access is still enabled on the DB, or PUT/GET has not been enabled | CPU settings and DB attributes |
| Cannot connect at all | IP addresses are on different subnets, the wrong LAN adapter is selected, or a firewall is blocking access | Network and PC |
| Cannot connect to the simulator | Standard S7-PLCSIM does not listen on TCP 102 | Requires a NetToPLCsim bridge or PLCSIM Advanced (S7-1500 only) |
The row I want to draw attention to is the first one. The word refused sounds like a permissions problem, but there are two unrelated causes. One is that the CPU does not allow an external partner to connect through PUT/GET. The other is that the DB being requested is optimized and has no fixed offsets to reference. The library asks to read "DB10, byte 0, length 8," but an optimized DB does not arrange its data at those positions, so there is nothing to return.
Three PLC setup steps, and who makes the decision
PUT/GET is disabled by default for a reason. It is not something a script author can simply ask to have enabled. The person who must tick this box is the owner of that PLC, and they must understand what they are opening up. The configuration is done in TIA and then has to be downloaded to the CPU, which is already the responsibility of the person looking after the machine.
- Go to CPU Properties > Protection & Security > Connection mechanisms and tick Permit access with PUT/GET communication from remote partner
- Create a separate export DB, such as DB_Export, go to Properties > Attributes, and clear Optimized block access. The DB will have fixed offsets, visible in the Offset column
- Have the program copy only the values intended for reading into DB_Export, then compile and download following the normal procedure for that machine
This checkbox has no "read-only" access level. Enabling it allows external partners both read and write access. If the machine belongs to a customer or a machine builder, that party must approve and enable it themselves. Do not ask for the project password and then enable access for yourself.
DB_Export: why not disable optimization on the working DB?
The tempting shortcut is to clear optimized access on the DB the program already uses, making every value readable. I do not do that for three reasons. First, it changes a DB that the actual program depends on for the benefit of an outside reader. Second, if someone later inserts a variable in the middle of the DB, all the offsets the script relies on will shift without warning. Third, every value in that DB becomes reachable by an external partner.
A separate export DB addresses all three points. The program chooses what to copy out, the DB_Export layout becomes an agreement between the PLC and the script that changes infrequently, and the working DB remains optimized.
DB_Export can be written as an external source as shown below. The variable types and their order determine the offsets. I have annotated the offsets in comments, but the authoritative values are those in TIA's Offset column after compilation. I covered the byte layout rules separately in the article on DB layouts on both sides.
DATA_BLOCK "DB_Export"
{ S7_Optimized_Access := 'FALSE' }
VERSION : 0.1
NON_RETAIN
STRUCT
Level : Real; // offset 0.0 ยาว 4 ไบต์
Run : Bool; // offset 4.0
Count : Int; // offset 6.0 ยาว 2 ไบต์ เริ่มที่ไบต์คู่
END_STRUCT;
BEGIN
END_DATA_BLOCK
// เรียกจาก OB1 ทุก scan: PLC เป็นฝ่ายเลือกว่าจะส่งออกอะไร
"DB_Export".Level := "DB_Process".TankLevel;
"DB_Export".Run := "iDB_M01".Run;
"DB_Export".Count := "DB_Process".PieceCount;
DB_Process and iDB_M01 are made-up names. After importing, check the DB number assigned by TIA as well. The PC example below assumes it is DB10.
Read-only access from the PC with python-snap7
Install the library first, then the core code is just four lines.
python -m pip install python-snap7
import snap7
from snap7.util import get_real, get_bool, get_int
c = snap7.client.Client()
c.connect("192.168.0.1", 0, 1) # S7-1200/1500 ใช้ rack 0 slot 1
data = c.db_read(10, 0, 8) # DB10 เริ่มไบต์ 0 ยาว 8 ไบต์
print(get_real(data, 0), get_bool(data, 4, 0), get_int(data, 6))
c.disconnect()
What I have prepared for actual use is a script that adds a wrapper around this core code. My rule is that the file must contain no write commands and no STOP/RUN commands at all, rather than including them and disabling them with a flag, because one typo can enable a flag. The part that decodes values according to the layout looks roughly like this.
import csv, json, time
import snap7
from snap7 import util
try: # ชื่อโมดูลเปลี่ยนระหว่างรุ่นของไลบรารี
from snap7.type import Areas
except ImportError:
from snap7.types import Areas
def decode(buf, layout):
"""layout เช่น 'Level:REAL:0,Run:BOOL:4.0,Count:INT:6'"""
out = {}
for item in layout.split(","):
name, typ, off = [s.strip() for s in item.split(":")]
typ = typ.upper()
if typ == "BOOL":
byte, bit = off.split(".")
out[name] = util.get_bool(buf, int(byte), int(bit))
elif typ == "INT":
out[name] = util.get_int(buf, int(off))
elif typ == "DINT":
out[name] = util.get_dint(buf, int(off))
elif typ == "REAL":
out[name] = round(util.get_real(buf, int(off)), 4)
elif typ == "WORD":
out[name] = util.get_word(buf, int(off))
else:
out[name] = "unsupported " + typ
return out
def trend(ip, db, size, layout, every=1.0, count=60, path="trend.csv"):
c = snap7.client.Client()
c.connect(ip, 0, 1)
try:
with open(path, "w", newline="", encoding="utf-8") as fh:
writer = None
for i in range(count):
row = {"t": time.strftime("%Y-%m-%d %H:%M:%S")}
row.update(decode(c.db_read(db, 0, size), layout))
if writer is None:
writer = csv.DictWriter(fh, fieldnames=list(row))
writer.writeheader()
writer.writerow(row)
print(json.dumps(row, ensure_ascii=False))
if i < count - 1:
time.sleep(every)
finally:
c.disconnect()
def read_memory_bytes(c, start, size):
return c.read_area(Areas.MK, 0, start, size) # พื้นที่ M อ่านอย่างเดียว
trend("192.168.0.1", 10, 8, "Level:REAL:0,Run:BOOL:4.0,Count:INT:6")
The full version accepts command-line parameters. It can decode BOOL (written as byte.bit), INT, DINT, REAL, WORD, DWORD, BYTE, and STRING. It is invoked like this.
# ข้อมูล CPU กับสถานะ
python snap7_probe.py 192.168.0.1 --info
# อ่าน DB10 ยาว 16 ไบต์ ถอดค่าตาม offset
python snap7_probe.py 192.168.0.1 --db 10 --size 16 --layout "Level:REAL:0,Run:BOOL:4.0,Count:INT:6"
# อ่านพื้นที่ M 4 ไบต์
python snap7_probe.py 192.168.0.1 --area M --start 0 --size 4
# เก็บ trend ทุก 1 วินาที 60 ครั้ง ลง CSV ให้ AI วิเคราะห์ต่อ
python snap7_probe.py 192.168.0.1 --db 10 --size 16 --layout "Level:REAL:0,Run:BOOL:4.0,Count:INT:6" --every 1 --count 60 --csv trend.csv
Collecting trends, counting downtime, and reading alarm words for later analysis: tasks where data arriving one second late causes no harm. This approach is not intended to control a machine. If you are thinking of having a script make decisions in place of the PLC, that task belongs in the PLC program in the first place.
PUT/GET has no authentication and must stay on an isolated network
This is the part I give the most weight to. PUT/GET has no authentication, no username, and no password. Anyone who can send packets to the CPU's TCP 102 can read, write, and stop the CPU just as my script can. A script with no write commands protects only against my own mistakes. It does not protect against other machines on the same LAN.
I set three conditions. The PLC network must be on a separate VLAN from the office network, access to TCP 102 must be restricted to a single reader machine, and this port must never be exposed to the internet under any circumstances. If a Linux router separates the two networks, the rules would look roughly like this.
# อนุญาตเฉพาะเครื่องอ่าน 192.168.10.50 เข้า TCP 102 ของ CPU
iptables -A FORWARD -p tcp -s 192.168.10.50 -d 192.168.0.1 --dport 102 -j ACCEPT
# ที่เหลือทั้งหมดที่จะเข้า TCP 102 ของวงควบคุม ทิ้ง
iptables -A FORWARD -p tcp -d 192.168.0.0/24 --dport 102 -j DROP
Port-level rules like these can restrict only who gets access. They cannot distinguish whether a packet passing through contains a read command or a write command. The authorized reader must therefore be a machine I can keep under control, not a laptop that connects to the internet elsewhere and then gets plugged back in. Devices on the same control network do not pass through this firewall at all. If that network contains other untrusted machines, the first condition still has not been met.
Never let AI or a script write values, issue STOP/RUN commands, or download to a PLC connected to machinery while people are on site. Every tool must default to read-only, and safety circuits such as E-Stop, safety doors, and light curtains must be hardwired or handled by an F-CPU, not depend on who sends what over TCP 102.
Ready-made MCP servers include tools to write and stop the CPU
Another thing I nearly overlooked was assuming a community-built runtime MCP server would be more convenient than writing my own. Only when I read the tool list did I see that these MCP servers wrap snap7 and expose the full set of tools, including writes, plc_stop, cold start, and hot start. Once registered with AI, the AI can see these tools and call them just like the read tools.
No write path in the file
It contains only connect, db_read, read_area, and CPU information reads. Results are output as JSON and CSV, then the files are passed to AI for analysis. The AI does not hold the PLC connection itself. The drawback is no live interaction: data collection has to run first.
Convenient, but includes tools that must be removed
AI can query live values immediately, but the tool set includes writes and CPU stop and start operations. Before connecting it to actual machinery, these tools must be removed from the code, or the server should not be used at all. Telling AI not to call them does not count as protection.
Personally, I choose the option on the left for PLCs connected to machinery. For a test bench where the CPU is not connected to anything, feel free to use the option on the right.
What remains unverified, and where to go next
To sum up, the established route for reading values from V15.1-era CPUs is snap7 over PUT/GET, with four things in place: the machine owner enables PUT/GET, a separate non-optimized export DB, a reader containing no write commands, and an isolated network with source restrictions. If any one is missing, I consider it too soon to enable access.
Here is what I have not done yet and do not want anyone to assume I have done.
- I have not run the script against a real PLC. The error messages in the table come from my research notes.
- I have not measured how much reading every 1 second affects the CPU's scan time.
- I have not tried connecting through a bridge to the simulator myself. The simulator limitations come from documentation.
- The firmware versions for Web API and OPC UA are approximate figures from my research. Before deciding, check them against the documentation for the actual CPU model in use.
If the device you want to read is a meter or inverter that already speaks Modbus, there is no need to take this route. That route is simpler and does not require enabling anything on the CPU. I covered it in the article on reading a meter over Modbus. Once I have tried this on real equipment, I will come back and update any results that differ from my notes.
Want us to set this up?
Get help with server setup, configuration, migration, or troubleshooting. Save time for the work that matters.
Hit something like this? Stuck somewhere?
Come trade notes on the LinuxThai board



Comments 0
No comments yet — be the first