2017-03-07 68 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))