Subscribing to data changes across multiple connections #1354
zaxarhic2134
started this conversation in
General
Replies: 1 comment
-
Normaly you would run a async task per connection. You can do this with asyncio.create_task and asyncio.gather. This is how i would do it (code not tested): class SubscriptionHandler:
def __init__(self, url, variable):
self.variable = variable
self._url = url
async def datachange_notification(self, node: Node, val, data):
"""
Callback for asyncua Subscription.
This method will be called when the Client received a data change message from the Server.
"""
_logger.info(f'datachange_notification Client: {self._url} : {self._id} {node} {val}')
async def run_loop(connection):
try:
async with OPCUAClient(connection.connection_data['uri'],
connection.connection_data['nsuri'],
connection.id) as OPCClient:
client = OPCClient.client
nodes = await get_variables(connection.id)
for variables in nodes:
handler = SubscriptionHandler(connection, variables.id)
subscription = await client.create_subscription(100, handler)
for nodeId in variables.variables:
node = client.get_node(nodeId)
handle = await subscription.subscribe_data_change(node)
while True:
await asyncio.sleep(1)
except Exception as e:
await set_connection_status(connection.id, 3)
print(e)
async def main():
tasks = [asyncio.create_task(run_loop(connection)) for connection in await get_connections()]
results = await asyncio.gather(*tasks) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
When executing the asyncio.run(main()) command, a for loop occurs in which data is obtained to create a client, and then a subscription to changing variables occurs, but due to the presence of "while True:" the process is blocked and, in fact, only one connection is processed
the output is only a subscription for one connection
How can I split the threads so that all connections are processed?
Beta Was this translation helpful? Give feedback.
All reactions