当前位置: 首页> 科技> IT业 > 小型办公室网络布线设计方案_女性pose拍照_搜索引擎关键词的工具_上海专业的seo推广咨询电话

小型办公室网络布线设计方案_女性pose拍照_搜索引擎关键词的工具_上海专业的seo推广咨询电话

时间:2025/7/17 1:06:19来源:https://blog.csdn.net/weixin_44656422/article/details/146608011 浏览次数:1次
小型办公室网络布线设计方案_女性pose拍照_搜索引擎关键词的工具_上海专业的seo推广咨询电话

 这里的重点是plc_connection,第一次建立client的时候,它会报错

连接失败,错误信息: b' TCP : Unreachable peer'

所以才建不了client,所以也get不了 plc data,所以才报错。

所以plc_connection一定要有重试机制!!!

import snap7
import struct
import timePLC_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 PLCexcept 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 valuedef is_connected(plc_obj):"""检查 PLC 是否仍然连接。通过尝试读取一个 DB 块来验证连接状态。"""try:# 尝试读取一个小型数据块(例如 2 字节)a=plc_obj.db_read(db_number=1200, start=0, size=2)return Trueexcept Exception as e:print(f"连接检测失败,错误信息: {e}")return Falsedef main():retry_delay = 2plc_obj = None  # 初始化 PLC 对象为 Nonewhile 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()

关键字:小型办公室网络布线设计方案_女性pose拍照_搜索引擎关键词的工具_上海专业的seo推广咨询电话

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: