继续自动搜索连接快照7

2024-09-28 22:19:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我们想通过wifi自动连接PLC。当树莓启动并自动运行他的程序时。它应该是一个独立的覆盆子,所以我们没有键盘或任何东西。我们通过snap7发送数据。 这是可行的,但是如果wifi断开连接,我会得到这样的错误:“ISO:An error occurred during recv TCP:Connection timeout” 有时在程序开始时我们会遇到这样的错误:“Snap7Exception:TCP:Unreachable peer”

我的程序停止,但我们应该有一些东西,以便我们的wifi重新连接,而不停止程序。我想我们需要一些东西来捕捉我们的错误,并在一个程序中使用它。在

我现在的计划是:

import snap7
import struct
import time
from snap7.snap7exceptions import Snap7Exception
import re
from ctypes import c_int, c_char_p, byref, sizeof, c_uint16, c_int32, c_byte
from ctypes import c_void_p

client = snap7.client.Client()

db_number = 109

print('Press Ctrl-C to quit.')

while True:

    if client.get_connected() == False: 
        client.connect('192.168.5.2', 0, 1) #('IP-address', rack, slot)
        print('not connected')
        time.sleep(0.2)
    else:
        print('connected')

Tags: fromimport程序clienttime错误ctypes树莓
2条回答

您可以使用try-exception连接和读取PLC,如以下代码:

from time import sleep
from snap7 import client as s7


def plc_connect(ip, rack, slot, stop_tries, freq):
    plc = s7.Client()
    tries = 1
    while tries < stop_tries and not plc.get_connected():
        try:
            print('trying for connecting to PLC ...')
            sleep(freq)
            plc.connect(ip, rack, slot)
            return True

        except Exception as e:
            logger.error("warning in PLC connection >>{}".format(e))
            sleep(freq)

            if tries == (stop_tries - 1):
                print('error in plc connection')
                return False

        tries += 1
    return False


def data_reader():
    plc = s7.Client()
    try:
        result, data_items = plc.read_multi_vars(data_items)
        return result, data_items
    except Exception as e:
        print('warning:>>{}'.format(e))

在python中,可以使用^{}语句捕捉错误。在

你可以沿着这条线试试:

while True:

    if client.get_connected() == False:
        try:
            client.connect('192.168.5.2', 0, 1) #('IP-address', rack, slot)
            print('not connected')
            time.sleep(0.2)
        except Snap7Exception as e:
            continue
    else:
        print('connected')

相关问题 更多 >