2017-03-07 71 views
1

我们希望通过wifi与PLC自动连接。当树莓启动并自动运行他的程序。它应该是一个独立的覆盆子,所以我们没有键盘或任何东西。我们通过snap7发送数据。 这个工程,但如果wifi断开,我得到这个错误:“ISO:在recv TCP期间发生错误:连接超时” 有时在程序的开始,我们得到这个错误:“Snap7Exception:TCP:Unreachable peer”自动搜索连接snap7

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

我在这一刻程序:

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') 

回答

1

在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') 
+0

它似乎做工精细!感谢您的支持! – Plessers

0

你可以使用“尝试异常”用于连接和读取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))