无法通过Python与Beckhoff TwinCAT PLC建立ADS连接,求帮助
问题描述
无法通过Python的pyads库连接Beckhoff TwinCAT PLC,报错信息为:Failed to open port on AMS router
代码示例
#running at sneha mam's laptop import pyads # Define the AMS Net ID and the port for ADS communication AMS_NET_ID = '192.168.1.6.1.1' # Your PLC's AMS Net ID ADS_PORT = 851 # Standard ADS port # def check_connection(): # Create a connection object print("Creating connection object...") plc = pyads.Connection(AMS_NET_ID, ADS_PORT) try: # Open the connection print("Opening connection...") plc.open() print("Connection to PLC successful.") except Exception as e: print(f"Failed to connect to PLC: {e}") finally: # Ensure the connection is closed if it was opened if plc.is_open: # Access as a property, not a method plc.close() print("Connection closed.") else: print("Connection was not open.")
运行输出
Creating connection object... Opening connection... Failed to connect to PLC: Failed to open port on AMS router. Connection was not open.
排查与解决步骤
检查TwinCAT ADS Router服务状态
打开Windows服务列表(按下Win+R,输入services.msc回车),找到TwinCAT ADS Router服务,确保它处于运行状态。若未运行,右键启动并设置启动类型为“自动”。验证AMS Net ID与端口正确性
确认PLC的AMS Net ID是否匹配:在TwinCAT工程中查看PLC设备属性里的AMS Net ID(通常格式为IP地址.1.1,需以实际配置为准);若使用TwinCAT 2,需将ADS端口改为801;执行ping 192.168.1.6测试网络连通性,确保设备在同一局域网。配置TwinCAT ADS路由表
打开TwinCAT XAE环境,点击顶部菜单栏TwinCAT>ADS Router>Edit Route,添加或确认客户端电脑的AMS Net ID(可通过客户端电脑adsroute.exe命令查看)与PLC的路由规则,确保允许客户端访问PLC的ADS端口。检查防火墙设置
临时关闭客户端和PLC设备的防火墙测试连接,若正常,再在两端添加允许ADS通信的规则:开放端口851(或801)的TCP/UDP流量。确认pyads与TwinCAT版本兼容性
TwinCAT 3建议使用pyads 3.x及以上版本,若版本不匹配,执行pip uninstall pyads后重新安装:pip install pyads。以管理员权限运行脚本
右键Python脚本或终端,选择“以管理员身份运行”,避免权限不足导致端口无法打开。
内容的提问来源于stack exchange,提问作者Angad Bandal

