Wednesday, May 11, 2016

snap7 reconnecting code snippet

In some cases your pi may lose connection with your PLC.. here's some helpful code to get it reconnected (I whipped this up pretty quick, and it's currently untested)
def connect(plc,ip):
    while True:
        #check connection
        if plc.get_connected():
            break
        try:
            #attempt connection
            plc.connect(ip,0,0)
        except:
            pass
        sleep(5)
        
plc = snap7.client.Client()
connect(plc,'10.10.55.109')
while True:    
    try:
        #do stuff 
                
    except Snap7Exception as e:
        connect(PLC)
        # break
connect(plc,ip) method puts your pi in an infinite loop till it is connected. make sure you wrap your methods with a try,except.

No comments:

Post a Comment