直接复制到pycHorm,修改ip地址和站地址就可以直接读取,有利于数据的处理
import struct
import time
import snap7
def plc_connect(ip, type, rack=0, slot=1):
"""
连接初始化
:param ip:
:param type::param connection_type: 1 for PG, 2 for OP, 3 to 10 for S7 Basic
:param rack: 通常为0
:param slot: 根据plc安装,一般为0或1
:return:client
"""
client = snap7.client.Client()
client.set_connection_type(type)
client.connect(ip, rack, slot)
return client
def plc_con_close(client):
"""
连接关闭
:param client:
:return:
"""
client.disconnect()
def read_VB(client, offset):
""" :param client: client
:param offset: int
:returns: str.
"""
vb_data = client.db_read(1, offset, 1)
return vb_data[0]
def write_VB(client, offset, data):
""" :param client: client
:param offset: int
:param data: str
"""
data = int(data)
temp = hex(int(data))[2:]
if data < 0 or data > 255:
print("请输入0-255之间的数")
else:
if data < 16:
temp = "0"+ temp
client.db_write(1, offset, bytes.fromhex(temp))
print("向寄存器VB"+str(offset)+"写入"+str(data)+"成功")
if __name__ == "__main__":
client_fd = plc_connect('192.168.2.1', 2)
print("connect success")
write_VB(client_fd, 1, "16")
data = read_VB(client_fd, 1)
print(data)
plc_con_close(client_fd)
def write_VD(client, offset, data):
temp = hex(int(data))
temp = temp[2:].zfill(8)
# print(type(temp))
try:
client.write_area(snap7.snap7types.areas.DB, 1, offset, bytes.fromhex(temp))
print("向寄存器VB"+str(offset)+"写入"+str(data)+"成功")
except Exception as e:
time.sleep(0.003)
write_VD(client, offset, data)
def read_VD(client, offset):
"""This is a lean function of Cli_ReadArea() to read PLC DB.
:param client: client
:param offset
:returns: data int.
"""
try:
v_data = client.read_area(snap7.snap7types.areas.DB, 1, offset, 4)
data = int.from_bytes(v_data, byteorder='big', signed=False)
except Exception as e:
time.sleep(0.003)
data = read_VD(client, offset)
return data
def write_VW(client, offset, data):
temp = hex(int(data))
temp = temp[2:].zfill(4)
# print(type(temp))
try:
client.write_area(snap7.snap7types.areas.DB, 1, offset, bytes.fromhex(temp))
print("向寄存器VB"+str(offset)+"写入"+str(data)+"成功")
except Exception as e:
time.sleep(0.003)
write_VW(client, offset, data)
def read_VW(client, offset):
"""This is a lean function of Cli_ReadArea() to read PLC DB.
:param client: client
:param offset
:returns: data int.
"""
try:
v_data = client.read_area(snap7.snap7types.areas.DB, 1, offset, 2)
data = int.from_bytes(v_data, byteorder='big', signed=False)
except Exception as e:
time.sleep(0.003)
data = read_VW(client, offset)
return data
楼主最近还看过