我们想通过无线网络与PLC自动连接。当树莓启动并自动运行他的程序时。它应该是一个独立的覆盆子,所以我们没有键盘或任何东西。我们通过snap7发送数据。这是可行的,但是如果wifi正在断开连接,我会得到以下错误:"ISO:在recv :连接超时期间发生的错误“--有时在程序开始时我们会得到这个错误:"Snap7Exception: TCP: Unreachable”
我的程序停止了,但是我们应该有一些东西,这样我们的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')发布于 2017-03-07 08:24:48
在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')发布于 2017-11-13 06:39:31
您可以使用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))发布于 2021-09-15 06:49:51
import time
import snap7
from snap7.exceptions import Snap7Exception
# client = snap7.client.Client()
connect = False
def dataPLC(client_):
print(client_.db_read(100, 10, 4))
time.sleep(2)
while True:
if not connect:
try:
client = snap7.client.Client()
client.connect('172.20.255.200', 0, 2)
time.sleep(1)
connect = client.get_connected()
print('plc connect ', connect)
except Snap7Exception as e:
connect = False
continue
else:
try:
if connect:
print('connection')
dataPLC(client)
except Snap7Exception as e:
client.destroy()
print('error ', e)
connect = False
continuehttps://stackoverflow.com/questions/42643340
复制相似问题