pythontcpraspberry-pi

Keep automatically searching for connection snap7


We want to autoconnect with the PLC through wifi. When the raspberry is starting up and runs his program automatically. It should be a stand alone raspberry so we don't have a keyboard or anything. We send the data via snap7. This works, but if the wifi is disconnecting I get this error: "ISO: An error occurred during recv TCP: Connection timed out" Sometimes in the beginning of the program we get this error: "Snap7Exception: TCP : Unreachable peer"

My program stops but we should have something so our wifi is reconnected again without stopping the program. I guess we need something to catch our error and use this in a program with a try or something.

My program at this moment:

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

Solution

  • In python you can catch errors with the try-except statement.

    You can try something along this line:

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