解决PLC通信会断然后报错的问题
这里的重点是plc_connection,第一次建立client的时候,它会报错
连接失败,错误信息: b' TCP : Unreachable peer'
所以才建不了client,所以也get不了 plc data,所以才报错。
所以plc_connection一定要有重试机制!!!
import snap7
import struct
import time
PLC_IP = '192.168.10.2'
def plc_connection(PLC_IP, retry_delay=2):
"""
尝试连接 PLC,无限重试,直到成功。
每次失败后等待 retry_delay 秒再重试。
"""
while True:
try:
PLC = snap7.client.Client()
PLC.connect(PLC_IP, rack=0, slot=2)
if PLC.get_connected():
print(f"成功连接到 PLC (IP: {PLC_IP})")
return PLC
except Exception as e:
print(f"连接失败,错误信息: {e}")
time.sleep(retry_delay) # 等待一段时间后重试
def get_plc_data(plc_obj, db):
data = plc_obj.db_read(db_number=db, start=0, size=2)
value = struct.unpack('!h', data)[0]
return value
def is_connected(plc_obj):
"""
检查 PLC 是否仍然连接。
通过尝试读取一个 DB 块来验证连接状态。
"""
try:
# 尝试读取一个小型数据块(例如 2 字节)
a=plc_obj.db_read(db_number=1200, start=0, size=2)
return True
except Exception as e:
print(f"连接检测失败,错误信息: {e}")
return False
def main():
retry_delay = 2
plc_obj = None # 初始化 PLC 对象为 None
while True:
try:
a=get_plc_data(plc_obj,1200)
print(a)
# 如果 PLC 对象不存在或连接已断开,则重新连接
# if plc_obj is None or not is_connected(plc_obj):
# if plc_obj is not None:
# try:
# plc_obj.disconnect() # 断开旧的连接(如果存在)
# except Exception as e:
# print(f"断开旧连接时出错: {e}")
# print("尝试重新连接 PLC...")
# plc_obj = plc_connection(PLC_IP, retry_delay=retry_delay)
# print('lianjie', plc_obj.get_connected())
# time.sleep(5)
except Exception as e:
print(f"发生未知错误: {e}")
print("等待 5 秒后重试连接...")
if plc_obj is not None:
try:
plc_obj.disconnect() # 断开旧的连接(如果存在)
except Exception as e:
print(f"断开旧连接时出错: {e}")
print("尝试重新连接 PLC...")
plc_obj = plc_connection(PLC_IP, retry_delay=retry_delay)
time.sleep(5) # 等待一段时间后重新尝试连接
if __name__ == '__main__':
main()