How to control scan time with asyncua library

46 Views Asked by At

I am experimenting with the python library asyncua. The program is communicating with an OPC server that is running on the same PC. the main_client() is reading one value, and printing another value. All of this is working as expected. I also added a function called tankFunction. That is just ramping up and down from 0 to 4 and down again (simulating filling and emptying a tank).

My issue is that I have to control the scan time of the function. I need to be able to get the tankFunction to run for example every second with some degree of precision. When I'm running this script it takes about 2 seconds between doing something, and I dont know where or how to manipulate that. If anybody knows where this is explained or could point me in the right direction it would be much appreciated!

Here is the code.

import asyncio
from asyncua import Client, ua
import datetime



url = "opc.tcp://localhost:4840"
namespace = "CODESYSSPV3/3S/IecVarAccess"

#Parameters
global u 
global ykm1
u = 1
ykm1 = 0

def tankFunction(l,w,h):
    global u
    global ykm1

    y = 0.25*u+ykm1

    if y < 0:
        y = 0
        u=0.1
    elif y > 4:
        y = 4
        u = -0.1
    ykm1 = y
    return y


async def main_client():

    print(f"Connecting to {url} ...")
    async with Client(url=url) as client:
        node = client.get_node("ns=4;s=|var|CODESYS Control Win V3 x64.Application.GVL_Modbus.Mb_Tank01_ManualDensity")
        var = await node.get_value()
        print(var)
        
        node2 = client.get_node("ns=4;s=|var|CODESYS Control Win V3 x64.Application.GVL_Modbus.Tank_01_Active")
        await node2.write_value(True, ua.Boolean)

        now = datetime.datetime.now()
        print(now.time())
        



while True:
    asyncio.run(main_client())
    print(tankFunction(1,5,3))


    

What is read in the terminal is this:

Connecting to opc.tcp://localhost:4840 ...

0 09:37:54.791759 0.25 Connecting to opc.tcp://localhost:4840 ...

0 09:37:56.913719 0.5 Connecting to opc.tcp://localhost:4840 ...

0 09:37:59.039703 0.75

The time between some of the scans are 2.122s, 2.126s, 2.121s, 2.126s.

I have experimented with asyncio.sleep() and tried reading the documentation in https://github.com/FreeOpcUa/opcua-asyncio/tree/master but I didnt understand how to solve this problem. I believe that my understanding of how asyncio is working is lacking.

0

There are 0 best solutions below