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

相关推荐
ℋᙚᵐⁱᒻᵉ鲸落25 分钟前
移动端滑动手势冲突:overflow: auto导致外层横向滑动失效
前端·javascript·css·vue.js·html
默_笙2 小时前
🎃 前端学了 Next.js,后端该学啥?NestJS 就是 Node 版的蜜雪冰城
前端·javascript
傲笑风2 小时前
【openvino】tinybert基于openvino服务化部署(四)
人工智能·python·自然语言处理·nlp·bert·openvino
weixin_416667962 小时前
【无标题】
运维·服务器·网络
维基框架3 小时前
WIKI 知识库 v1.1.1 正式发布
人工智能·python
予昊3 小时前
从零实现“在线五子棋对战“:WebSocket 实时通信 + 段位匹配
java·开发语言·网络·websocket
前端snow3 小时前
ai agent --- 实现 openclaw 定时间效果
前端
码云之上3 小时前
换模型之后,Chatbot 为什么要自己做 compact?
前端·agent·前端工程化
星栈3 小时前
自定义 UI-UX-Pro-Max 的 CSV 知识库,把 AI 生成的后台拉回行业该有的样子
前端·agent·weui
研☆香3 小时前
简单的图片上传 删除 预览
前端