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

相关推荐
yaoh.wang7 小时前
力扣(LeetCode) 13: 罗马数字转整数 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
AI浩7 小时前
【Labelme数据操作】LabelMe标注批量复制工具 - 完整教程
运维·服务器·前端
涔溪7 小时前
CSS 网格布局(Grid Layout)核心概念、基础语法、常用属性、实战示例和进阶技巧全面讲解
前端·css
2401_878454537 小时前
浏览器工作原理
前端·javascript
西陵7 小时前
为什么说 AI 赋能前端开发,已经不是选择题,而是必然趋势?
前端·架构·ai编程
小鸡吃米…7 小时前
Python PyQt6教程七-控件
数据库·python
1916zz8 小时前
Extreme programing 方利喆 _ 江贤晟
python
长安牧笛8 小时前
智能鞋柜—脚气终结者,内置温湿度传感器和紫外线灯,晚上回家,把鞋放进去,自动检测湿度,湿度超标就启动烘干+紫外线杀菌,第二天穿鞋干燥无异味。
python
鲨莎分不晴8 小时前
强化学习第五课 —— A2C & A3C:并行化是如何杀死经验回放
网络·算法·机器学习
weixin_457760008 小时前
PIL库将图片位深度是1、8、32统一转换为24的方法
python