client.py 存取 西门子PLC数据的客户端例子
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Project: pi4b_aliyuniot
# File : snap_client.py
# Author : Long.Xu <fangkailove@yeah.net>
# http://gnolux.blog.csdn.net
# QQ:26564303
# Time : 2021/4/7 2:14 下午
# Copyright 2021 Long.Xu All rights Reserved.
from snap7 import util, client
from snap7.types import S7AreaMK,S7AreaDB
my_plc = client.Client()
# my_plc.set_connection_type(3)
# -------------------------------------------
# plc rack and slot value table
# -------------------------------------------
# plc rack slot
# -------------------------------------------
# s7-200smart 0 1
# s7-300 0 2
# s7-400/WIN AC 见硬件组态 见硬件组态
# s7-1200/1500 0 0/1
# -------------------------------------------
my_plc.connect('127.0.0.1', rack=0, slot=1, tcpport=502)
byte_arrays = my_plc.read_area(area=S7AreaMK, dbnumber=0, start=0, size=2)
print('赋值前', util.get_bool(byte_arrays, 0, 0))
util.set_bool(byte_arrays, 0, 0, False)
my_plc.write_area(S7AreaMK, 0, 0, byte_arrays)
print('赋值后', util.get_bool(byte_arrays, 0, 0))
util.set_bool(byte_arrays, 1, 1, False)
my_plc.write_area(S7AreaMK, 2, 0, byte_arrays)
# DB区和200samart的V区,dbnumber 填 1, 其它填0
byte_arrays = my_plc.read_area(S7AreaDB, 1, 3222, 2)
print('赋值前', util.get_word(byte_arrays, 0))
util.set_word(byte_arrays, 0, 199)
my_plc.write_area(S7AreaDB, 1, 3222, byte_arrays)
print('赋值后', util.get_word(byte_arrays, 0))
my_plc.disconnect()
my_plc.destroy()
Server.py 模拟西门子plc 的例子
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Project: pi4b_aliyuniot
# File : snap_server.py
# Author : Long.Xu <fangkailove@yeah.net>
# http://gnolux.blog.csdn.net
# QQ:26564303
# Time : 2021/4/7 2:14 下午
# Copyright 2021 Long.Xu All rights Reserved.
import time
import logging
import snap7
logger = logging.getLogger(__name__)
def mainloop(tcpport: int = 1102):
server = snap7.server.Server()
size = 999999
DBdata = (snap7.types.wordlen_to_ctypes[snap7.types.S7WLByte] * size)()
PAdata = (snap7.types.wordlen_to_ctypes[snap7.types.S7WLByte] * size)()
TMdata = (snap7.types.wordlen_to_ctypes[snap7.types.S7WLByte] * size)()
CTdata = (snap7.types.wordlen_to_ctypes[snap7.types.S7WLByte] * size)()
MKdata = (snap7.types.wordlen_to_ctypes[snap7.types.S7WLByte] * size)()
server.register_area(snap7.types.srvAreaDB, 1, DBdata)
server.register_area(snap7.types.srvAreaPA, 1, PAdata)
server.register_area(snap7.types.srvAreaTM, 1, TMdata)
server.register_area(snap7.types.srvAreaCT, 1, CTdata)
server.register_area(snap7.types.srvAreaMK, 1, MKdata)
server.start(tcpport=tcpport)
while True:
while True:
event = server.pick_event()
if event:
logger.info(server.event_text(event))
else:
break
time.sleep(1)
mainloop(502)
西门子plc的读写,可以用 snap7库,参考官网: Snap7 Homepage
标签:snap7,python,读写,server,arrays,plc,PLC,byte,types From: https://blog.51cto.com/fangkailove/5881791