我们希望通过wifi与PLC自动连接。当树莓启动并自动运行他的程序时。它应该是一个独立的覆盆子,所以我们没有键盘或任何东西。我们通过snap7发送数据。 这是有效的,但如果wifi断开连接,我会收到此错误:“ISO:在recv TCP期间发生错误:连接超时” 有时在程序开始时我们会收到此错误:“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')
答案 0 :(得分:2)
在python中,您可以使用try-except
语句捕获错误。
您可以尝试这一行:
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')
答案 1 :(得分:1)
You could use try-exception
for connecting and reading the PLC, such as below code:
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))