FreeOpcUa / python-opcua

LGPL Pure Python OPC-UA Client and Server
http://freeopcua.github.io/
GNU Lesser General Public License v3.0
1.32k stars 661 forks source link

Continues connection to opc ua - kepserver, and flask rest api #1518

Closed rherbut closed 1 year ago

rherbut commented 1 year ago

Hi i want to create rest api aplication to create web-scada app.

I don't know how to create continues connection to opc ua- kepserver and in the same time have flask python restapi.

I would like to create rest api server when i get request for example: http://127.0.0.1:5000/tags with json. So i will parse json, take to list and create request to kepserver for all tags from json.

But i have problem to have async connection and mix it with flask.

from flask import Flask import asyncio from asyncua import Client, ua, Node from asyncua.common.events import Event

trigger = False

async def opcua_client(): server_url = "opc.tcp://localhost:49320" client = Client(url=server_url,timeout=10) await client.set_security_string("Basic256Sha256,SignAndEncrypt,cert.pem,key.pem") client.application_uri = "" client.set_user("user") client.set_password("passoword") await client.connect() print("Połączono z serwerem OPC UA Kepware")

while True:
    if trigger == True:
        try:
            value = client.get_node("ns=2;s=EM_InputConditioning.CPF1_cisn_powr.Value").get_value()
            print("Wartość tagu:", value)
            trigger = False
        except Exception as e:
            print("Błąd pobierania wartości tagu:", e)
    else:
        asyncio.sleep(1)
client.disconnect()

def flask(): app = Flask(name)

@app.route("/")
def index():
    return "Hello World!"

@app.route("/tag")
def tag():
    trigger = True
    return None
app.run()

if name == 'main': asyncio.ensure_future(opcua_client()) asyncio.ensure_future(flask()) asyncio.get_event_loop().run_forever()

oroulet commented 1 year ago

you reported that question at the wrong place. Looks at https://github.com/FreeOpcUa/opcua-asyncio Also your code formating is broken. But generally flask and opcua-asyncio will work nicely together