先推荐一篇知乎上的文章,讲的非常详细. 使用Snap7读写西门子S7系列PLC
但,可能存在版本不同的问题,很多地方不能正常运行.下面贴出的是测试代码:
环境 python 3.8.4 (snap7 目前需要工作在 python3.6+,我经常用的是python3.4.4,这是支持XP的最后一个版本,已确定这个版本连import snap7 都报错)
snap7 python-snap7 1.2
>>> from snap7 import client >>> from snap7.types import areas >>> type(areas) <class 'snap7.common.ADict'> >>> areas['MK'] 131 # 按推荐文档连接PLC 成功 >>> plc = client.Client() >>> plc.set_connection_type(2) >>> plc.connect('192.168.2.1',0,1) >>> plc.get_connected() True # 但读数据时报错 >>> 读出的字节组 = plc.read_area(areas['MK'],0,1,1) Traceback (most recent call last): File "<pyshell#30>", line 1, in <module> 读出的字节组 = plc.read_area(areas['MK'],0,1,1) File "C:\Python38\lib\site-packages\snap7\client.py", line 390, in read_area if area not in Areas: File "C:\Python38\lib\enum.py", line 315, in __contains__ raise TypeError( TypeError: unsupported operand type(s) for 'in': 'int' and 'EnumMeta' # 打算读的是 200smart 的VB10,尝试用GitHub下载的源码中的例子尝试 # 但不清楚plc.db_read(0,10,1)的第一个参数应该怎么填,最后试出,对于200smart,应该填1 >>> 读出的字节组 = plc.db_read(0,10,1) b'CLI : function refused by CPU (Unknown error)' Traceback (most recent call last): File "<pyshell#31>", line 1, in <module> 读出的字节组 = plc.db_read(0,10,1) File "C:\Python38\lib\site-packages\snap7\client.py", line 226, in db_read check_error(result, context="client") File "C:\Python38\lib\site-packages\snap7\common.py", line 89, in check_error raise RuntimeError(error) RuntimeError: b'CLI : function refused by CPU (Unknown error)' >>> 读出的字节组 = plc.db_read(1,10,1) >>> 读出的字节组 bytearray(b'\x0f') # 通过查看源码,找到了正确的 read_area()的使用办法 >>> from snap7.types import Areas # Area.DB 指300,400,1200,1500中的DB块,也指200smart中的V区(相当于DB1) # DB号填错,被PLC拒绝 >>> 读出的字节组 = plc.read_area(Areas.DB,0,10,1) b'CLI : function refused by CPU (Unknown error)' Traceback (most recent call last): File "<pyshell#39>", line 1, in <module> 读出的字节组 = plc.read_area(Areas.DB,0,10,1) File "C:\Python38\lib\site-packages\snap7\client.py", line 403, in read_area check_error(result, context="client") File "C:\Python38\lib\site-packages\snap7\common.py", line 89, in check_error raise RuntimeError(error) RuntimeError: b'CLI : function refused by CPU (Unknown error)' # 正确读出VB10 >>> 读出的字节组 = plc.read_area(Areas.DB,1,10,1) >>> 读出的字节组 bytearray(b'\x1f') >>> plc.read_area(Areas.DB,1,10,1) bytearray(b'\x0f') >>> dir(Areas) ['CT', 'DB', 'MK', 'PA', 'PE', 'TM', '__class__', '__doc__', '__members__', '__module__'] >>> Areas.PA <Areas.PA: 130> >>> type(Areas.PA) <enum 'Areas'> >>> Areas.PE <Areas.PE: 129> # 尝试写入数据,在step7上验证成功 >>> 读出的字节组[0] = 0xFF >>> plc.db_write(1,10,读出的字节组) >>>View Code
标签:__,200,字节,snap7,python,读出,read,plc From: https://www.cnblogs.com/jichao1515/p/16981156.html