Checking connection with PLC Snap7 Python

1k views Asked by At

I made a program in Python with Snap7 library. I can read and write different variables without any problem. To finish it I need to check the communication with the PLC all the time. I checked I can use "get_connected()", but this works as I want only when I stablish the communication, but this get_ ... does not change the value when I remove the connection after I began the communication. Can some one help me to resolve this?

from tkinter import *
import snap7

IP='192.168.1.71'
Rack = 0
Slot = 1
PLC_Conectado = False
plc = snap7.client.Client()



tk = Tk()

def Conexion():
    if not plc.get_connected():
        try:
            plc.connect(IP,Rack,Slot)
        except:
            print("Error")
    print("Conexion:", plc.get_connected())
    tk.after(5, Conexion)

Conexion()

tk.mainloop()

I want to have any variable in order to get the state of connection

1

There are 1 answers

0
Osvaldo Aveni On

I could find a solution. With this code, the program reestablishes the connection when the plc is present again.

import snap7
IP='192.168.1.71'
Rack = 0
Slot = 1
PLC_Conectado = False
plc = snap7.client.Client()

def ConexionPLC():
    global PLC_Conectado, plc
    try:
        #plc = snap7.client.Client()
        if not plc.get_connected() or plc.get_cpu_state() == 'S7CpuStatusUnknown' :
            
            #try:
                plc.connect(IP,Rack,Slot)
                if plc.get_connected() and plc.get_cpu_state() != 'S7CpuStatusUnknown':
                    PLC_Conectado = True
                else: 
                    PLC_Conectado = False
    except:
        if PLC_Conectado:
            plc.destroy()
            plc = snap7.client.Client()
        PLC_Conectado = False