Siemens Smart 200 PLC 通讯(基于python-)

xml 复制代码
import struct
import time
import snap7
from snap7.util import *


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 read_area(client, offset):
   """ :param client: client
      :param offset: int
      :returns: str.
   """
   i0_0 = client.read_area(snap7.types.Areas.I, 0, 1)
   # eb_data = .eb_read(10, 5)
   return i0_0


def read_I(client):
      """
        I输入状态区的读操作-------------bool
        :param byte:
        :param bit:
        :return:
        """
      data = client.read_area(snap7.types.Areas.PE, 0, 0 ,1) # i0.0的 一个字节
      print(get_bool(data, 0, 0)) # i0.0的 一个字节


def read_Q(client):
   """
    Q电磁线圈状态区的读操作-------------bool
    :param byte:
    :param bit:
    :return:
    """
   data = client.read_area(snap7.type.Areas.PA, 0, 0, 1)  # i0.0的 一个字节
   print(get_bool(data, 0, 0))  # i0.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))
      # client.
      print("向寄存器VB"+str(offset)+"写入"+str(data)+"成功")

if __name__ == "__main__":

   client_fd = plc_connect('192.168.0.2', 2)
   print("connect success")   
   print(read_Q(client_fd))
   # write_VB(client_fd,0,210)
   plc_con_close(client_fd)

调试

通过设置plc软件中的Q0.0的程序,完成联通及状态读取

参考:https://python-snap7.readthedocs.io/en/latest/index.html

相关推荐
sunshineine1 小时前
jupyter notebook运行简单程序
linux·windows·python
方博士AI机器人1 小时前
Python 3.x 内置装饰器 (4) - @dataclass
开发语言·python
万能程序员-传康Kk1 小时前
中国邮政物流管理系统(Django+mysql)
python·mysql·django
月月大王1 小时前
easyexcel导出动态写入标题和数据
java·服务器·前端
Logintern091 小时前
【每天学习一点点】使用Python的pathlib模块分割文件路径
开发语言·python·学习
O。o.尊都假都2 小时前
UDP协议
linux·服务器·网络·网络协议·udp
开开心心_Every2 小时前
手机隐私数据彻底删除工具:回收或弃用手机前防数据恢复
android·windows·python·搜索引擎·智能手机·pdf·音视频
科技小E2 小时前
国标GB28181视频平台EasyCVR安防系统部署知识:如何解决异地监控集中管理和组网问题
大数据·网络·人工智能·音视频
Nina_7172 小时前
Day 14 训练
python
JC_You_Know2 小时前
多语言网站的 UX 陷阱与国际化实践陷阱清单
前端·ux