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

相关推荐
2601_967979124 小时前
初学者必知的Python中优雅的用法
python·枚举·初学者·优雅用法·字典解析
FRing035 小时前
vue2干货总结12(loading效果、全局前置导航守卫、搜索历史管理)
开发语言·前端·javascript·vue.js·vue2
YIAN5 小时前
我踩完 DeepAgents 记忆模块的坑,才搞懂长期记忆和摘要不是一回事
前端·javascript·agent
AI创界者6 小时前
Python 进阶实战(五十八章):配置热更新、优雅停机排空与高并发压测方案
人工智能·python·aigc
buhuizhiyuci7 小时前
websocket的介绍
网络·websocket·网络协议
map_3d_vis7 小时前
百度地图 JSAPI 4.0 是什么:版本说明与能力概览
前端·javascript·webgl·地图·百度地图
码云之上7 小时前
微信小程序设备指纹实践,删了重装还能认出这台手机吗?
前端·安全·微信小程序
JavaGuide7 小时前
刚刚,GLM-5.4 正式发布,实测来了:看图用 Blender 建凉亭、做技术视频,再画一辆真能传动的自行车
前端·后端
乌鲁木齐德润恒圣信息科技有限公司9 小时前
GEO生成式引擎优化:技术原理与43引擎自动测试系统
大数据·前端·人工智能
2601_9679873710 小时前
python网络工程师自动化运维课程
python·正则表达式·网络工程师·模块·自动化运维