代码基本逻辑

业务逻辑:我要给plc传一个值a=7,我要去检验plc有没有收到这个值,如果没有收到这个值,我要再传一遍值,直到plc里真的收到这个值了

简洁版:循环发送值直到PLC接收到指定值为止

代码逻辑:一直发a的值给plc,检查plc有没有收到

import snap7

def check_plc_value(ip_address, value):
    # Snap7连接PLC
    plc = snap7.client.Client()
    plc.connect(ip_address, 0, 1)

    # 循环发送值直到PLC接收到指定值为止
    while True:
        # 发送值到PLC
        plc.db_write(1, 0, [value])

        # 读取DB块的值
        db_data = plc.db_read(1, 0, 1)
        db_value = snap7.util.get_int(db_data, 0)

        if db_value == value:
            # 当PLC接收到指定值时,退出循环
            print("PLC received the value successfully.")
            break
        else:
            # 当PLC没有接收到指定值时,继续发送值
            print("PLC did not receive the value, sending again...")

    # 断开连接
    plc.disconnect()
import snap7

def connect_plc(ip_address):
    # Snap7连接PLC
    plc = snap7.client.Client()
    plc.connect(ip_address, 0, 1)
    return plc

def send_value_to_plc(plc, db_number, start_address, value):
    # 将值写入DB块
    plc.db_write(db_number, start_address, snap7.util.to_byte(value))

def check_value_received(plc, db_number, start_address, expected_value):
    # 检查PLC是否收到了值
    db_data = plc.db_read(db_number, start_address, 2)
    received_value = snap7.util.get_int(db_data, 0)
    return received_value == expected_value

# 使用示例
plc = connect_plc('192.168.1.100')
db_number = 1
start_address = 0
value = 7

while True:
    # 将值写入PLC
    send_value_to_plc(plc, db_number, start_address, value)

    # 检查PLC是否收到了值
    if check_value_received(plc, db_number, start_address, value):
        print("PLC received the value successfully.")
        break
    else:
        print("PLC didn't receive the value, retrying...")

 

你可能感兴趣的:(python)