python-opcua icon indicating copy to clipboard operation
python-opcua copied to clipboard

Connection loss by client

Open ghost opened this issue 7 years ago • 5 comments

Hi all, I am trying to identify a problem, which only occurs when using the server of my customer. Unfortunately, I can not reconstruct this issue, because I have no access to their network/server - which makes the troubleshooting difficult... When using my server, the below error message never occurs. Please notice that the error occurs after my client successfully connected and also read values.

WARNING:opcua.client.ua_client.Socket:ServiceFault from server received while waiting for publish response
ERROR:concurrent.futures:exception calling callback for <Future at 0x4470c18 state=finished returned Buffer>
Traceback (most recent call last):
  File "C:\python37\lib\concurrent\futures\_base.py", line 324, in _invoke_callbacks
    callback(self)
  File "C:\python37\lib\site-packages\opcua\client\ua_client.py", line 463, in _call_publish_callback
    self._uasocket.check_answer(data, "while waiting for publish response")
  File "C:\python37\lib\site-packages\opcua\client\ua_client.py", line 88, in check_answer
    hdr.ServiceResult.check()
  File "C:\python37\lib\site-packages\opcua\ua\uatypes.py", line 233, in check
    raise UaStatusCodeError(self.value)
opcua.ua.uaerrors._auto.BadSessionClosed: The session was closed by the client.(BadSessionClosed)
WARNING:opcua.client.ua_client.Socket:ServiceFault from server received while waiting for publish response
ERROR:concurrent.futures:exception calling callback for <Future at 0x4470048 state=finished returned Buffer>
Traceback (most recent call last):
  File "C:\python37\lib\concurrent\futures\_base.py", line 324, in _invoke_callbacks
    callback(self)
  File "C:\python37\lib\site-packages\opcua\client\ua_client.py", line 463, in _call_publish_callback
    self._uasocket.check_answer(data, "while waiting for publish response")
  File "C:\python37\lib\site-packages\opcua\client\ua_client.py", line 88, in check_answer
    hdr.ServiceResult.check()
  File "C:\python37\lib\site-packages\opcua\ua\uatypes.py", line 233, in check
    raise UaStatusCodeError(self.value)
opcua.ua.uaerrors._auto.BadSessionClosed: The session was closed by the client.(BadSessionClosed)

The Code I am using looks like this:

import sys
from threading import Thread
import logging
import time
from opcua import Client, ua
from opcua import Subscription
import xlrd
import os
from os.path import dirname

sys.path.insert(0, "..")

opc_connected = False

class SubHandler1(object):
    def datachange_notification(self, node, val, data):
        print("Data changed.", node, val)
        CallViews()


class SubHandler2(object):
    def datachange_notification(self, node, val, data):
        print("OPC UA server state changed.")

class CallViews(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True
        self.running = True
        self.start()

    def stop(self):
        self.running = False

    def run(self):
        while self.running:
            try:
                read_Laser1_PartID()
                read_Laser1_Values()
                self.stop()
            except:
                print("Could not load changed data.")
        else:
            self.stop()

class ConnectionChecker(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True
        self.running = True
        self.start()

    def stop(self):
        disconnect()
        self.running = False

    def run(self):
        while self.running:
            if opc_connected:
                time.sleep(1) 
                try:
                    print("Checking server connection.")
                    if not status.get_value() == 0:  #
                        print("Connection to OPC UA server failed. Please reconnect.")
                        self.stop()
                except:
                    print("Connection to OPC UA server failed.")
                    self.stop()
            else:
                self.stop()
        else:
            self.stop()

def loadSettings():
    workingdir = os.path.dirname(os.path.realpath(__file__))
    global ServerState, values_Laser1, partID_Laser1

    try:
        book_opcua = xlrd.open_workbook(workingdir + '/Settings.xls')
        sheet_opua = book_opcua.sheet_by_index(0)

        measurementServerAddress = sheet_opua.cell_value(18, 0)
        ServerState = sheet_opua.cell_value(21, 0)
        values_Laser1 = sheet_opua.cell_value(23, 0)
        partID_Laser1 = sheet_opua.cell_value(24, 0)
       
        print("Successfully loaded OPC UA settings.")

    except FileNotFoundError:
        print("Could not load OPC UA settings! Check settings file.")


def connect():
    global measurementServer, opc_connected
    logging.basicConfig(level=logging.WARN)

    measurementServer = Client(measurementServerAddress)

    params = ua.CreateSubscriptionParameters()
    params.RequestedPublishingInterval = 500
    params.RequestedLifetimeCount = 3000
    params.RequestedMaxKeepAliveCount = 10000
    params.MaxNotificationsPerPublish = 10000
    params.PublishingEnabled = True
    params.Priority = 0

    measurementServer.connect()
    opc_connected = True

    trigger = measurementServer.get_node(partID_Laser1)

    handler1 = SubHandler1()
    sub1 = measurementServer.create_subscription(params, handler1)
    handle1 = sub1.subscribe_data_change(trigger)
    time.sleep(0.1)

    handler2 = SubHandler2()
    sub2 = measurementServer.create_subscription(params, handler2)
    global status
    status = measurementServer.get_node(ServerState)
    handle2 = sub2.subscribe_data_change(status)
    time.sleep(0.1)
    ConnectionChecker()

    print("Connected to OPC UA server.")


def disconnect():
    try:
        measurementServer.disconnect()
        opc_connected = False
        print("Disconnected from OPA UA server.")
    except:
        opc_connected = False


def read_Laser1_PartID():
    try:
        partID = measurementServer.get_node(partID_Laser1)
        partID_value = partID.get_value()
        print("PartID: " + str(partID_value))
    except:
        disconnect()
        print("OPC UA error while trying to read partID.")


def read_Laser1_Values():
    try:
        values1 = measurementServer.get_node(values_Laser1)
        values1_value = values1.get_value()
        print("Laser1 Values: " + str(values1_value))
    except:
        disconnect()
        print("OPC UA error while trying to read Laser1 values.")

if __name__ == "__main__":
    loadSettings()
    connect()
    read_Laser1_PartID()
    read_Laser1_Values()

I have some guesses what the problem could be:

  1. Creating a new thread called by the subscription is the problem.
  2. The subscription event gets called 2x times after connecting to the server.
  3. Parameter settings e.g. params.RequestedMaxKeepAliveCount = 10000 or params.MaxNotificationsPerPublish = 10000

Thank you very much for your support!

ghost avatar Apr 18 '19 14:04 ghost

Hi @OPCle I am facing the same issue, did you find anything that caused the issue?

jkbngl avatar Jan 26 '20 21:01 jkbngl

Hi, @jkbngl Not really..., but I guess that it was caused by to heavy reading. So, what I did (and now it's working):

  1. Try it with only reading one value - does the error still occur?

  2. I am currently using these parameters for my client:

params = ua.CreateSubscriptionParameters()
params.RequestedPublishingInterval = 500
params.RequestedLifetimeCount = 3000
params.RequestedMaxKeepAliveCount = 10000
params.MaxNotificationsPerPublish = 2147483647
params.PublishingEnabled = True
params.Priority = 0
  1. Added some time.sleep(0.1) after reading a value so the server can process everything.

I hope it helps you.

ghost avatar Jan 27 '20 10:01 ghost

Your issue is not very well formatted and is hard to read. I don't think many people will help you with a post like this.

Anyways you are doing some things I definitely don't understand. Why do you need a thread to read values? Why does reading the values have to get the node every time the function is called? Why not just create a subscription for all your laser/quality values?

zerox1212 avatar Jan 27 '20 15:01 zerox1212

Yes, you're right..sorry - tried to fix the code highlighting.

  1. I am creating threads because the python example says for SubHandlers:

Subscription Handler. To receive events from server for a subscription data_change and event methods are called directly from receiving thread. Do not do expensive, slow or network operation there. Create another thread if you need to do such a thing

Without these threads it is not working.

  1. The values are not very often read (~every 15 minutes during production) and to make a subscription for each value seems to be a little much. Because of that I am subscribing only to one node and read the others after this one changed.

ghost avatar Jan 27 '20 16:01 ghost

I see. If this code works when using your own network/server then isn't it more likely a network or infrastructure issue? What UA server are you connecting to?

zerox1212 avatar Jan 28 '20 04:01 zerox1212