I created a basic python script to connect to PLC using pyads from my backend server. However, I am getting an Attribute Error: 'Connection' object has error has no attribute '_open'
Additional Details:
Ubuntu 20.04.2 LTS
Error Output -
File "testOne.py", line 28, in <module>
connect_to_plc(plc_ip, ams_net_id, ams_port)
File "testOne.py", line 19, in connect_to_plc
except pyads.AdsException as e:
AttributeError: module 'pyads' has no attribute 'AdsException'
Exception ignored in: <function Connection.__del__ at 0x7f3985d93e60>
Traceback (most recent call last):
File "/home/ubuntu/virtual_env/venv_with_python3.7/lib/python3.7/site-packages/pyads/connection.py", line 168, in __del__
self.close()
File "/home/ubuntu/virtual_env/venv_with_python3.7/lib/python3.7/site-packages/pyads/connection.py", line 204, in close
if not self._open:
AttributeError: 'Connection' object has no attribute '_open'
My Code -
import pyads
def connect_to_plc(plc_ip, ams_net_id, ams_port):
try:
# Connect to the PLC
ads = pyads.Connection(plc_ip, ams_net_id, ams_port)
# Open a connection
ads.open()
print(f"Connected to PLC {plc_ip} on {ams_net_id}:{ams_port}")
# Add your PLC communication logic here
# Close the connection when done
ads.close()
print("Connection closed.")
except pyads.AdsException as e:
print(f"Error: {e}")
if __name__ == "__main__":
# Replace these values with your PLC information
plc_ip = "<ip>" # Replace with your PLC IP address
ams_net_id = "<net_id>" # Replace with your AMS Net ID
ams_port = 851 # Replace with your PLC AMS port number
connect_to_plc(plc_ip, ams_net_id, ams_port)
Troubleshooting steps taken:
I checked pyads github and found a recent issue regarding pyads not working.
The suggested solution was downgrade the python version to 3.7
I followed the instructions from this thread to create a virtual environment and install python3.7.
However, the same error code appeared.
Checked my PLC IP address and AMS net ID. All are correct and I am able to ping my PLC without any issue
You have to create a route before trying to connect. You can follow the steps in pyads documentation page.
I created the route using add_route_to_plc function before establishing the connection. Example is below
ROUTE_NAME = "route-to-my-plc"
pyads.add_route_to_plc(
CLIENT_NETID, CLIENT_IP, TARGET_IP, TARGET_USERNAME, TARGET_PASSWORD,
route_name=ROUTE_NAME
)
Problem solved