stlehmann / pyads

Python wrapper for TwinCAT ADS
MIT License
252 stars 93 forks source link

Multiple pyads instances #314

Closed cisk closed 2 years ago

cisk commented 2 years ago

Hello, I am trying to run two instances of pyads on the same raspberry without success. I noticed that the port (open_port) has always the same value. Doing the same on Windows the port value changes.

How can I run two or more instances with pyads on the same system?

chrisbeardy commented 2 years ago

Try something similar to this:

import threading
import time

import pyads

def connect_and_read():
    with pyads.Connection("39.22.134.140.1.1", 851, "192.168.56.105") as plc:
        print(plc.get_local_address())
        time.sleep(3)

if __name__ == '__main__':  
    thread_1 = threading.Thread(target=connect_and_read)
    thread_2 = threading.Thread(target=connect_and_read)
    thread_1.start()
    thread_2.start()

You should get an output like this:

<AmsAddress 172.16.1.105.1.1:32908>
<AmsAddress 172.16.1.105.1.1:32909>

Showing different ports have been opened. You can alos create two instances of the Connection class to achieve the same thing e.g.

plc_1 = pyads.Connection("39.22.134.140.1.1", 851)
plc_2 = pyads.Connection("39.22.134.140.1.1", 851)

I only ran this RaspberryPiOs on a VM and not on a barebones pi but this should not make a difference.

I also tried this with multprocessing e.g.

import multiprocessing
import threading
import time

import pyads

def connect_and_read():
    with pyads.Connection("10.0.2.15.1.1", 851) as plc:
        print(plc.read_by_name("MAIN.counter"))
        print(plc.get_local_address())
        time.sleep(3)

if __name__ == '__main__':  
    thread_1 = threading.Thread(target=connect_and_read)
    thread_2 = threading.Thread(target=connect_and_read)
    thread_1.start()
    thread_2.start()

    mp_1 = multiprocessing.Process(target=connect_and_read)
    mp_2 = multiprocessing.Process(target=connect_and_read)
    mp_1.start()    
    mp_2.start()

This works on windows and ubuntu and freebsd, but not on raspberry pi...it appears raspberry pi does not like a second process being created. If threading / two connection classes are not ok, you could try using ubuntu os on the pi.

Thank you for your question on here. However in order to help manage the project, we ask that questions surroundiing usage of pyads are kept out of the issues. Stack Overflow and Reddit are great alternative places, r/PLC is quite active. Please could you close this issue, thanks.

chrisbeardy commented 2 years ago

@stlehmann this can be closed now