PIconnect
PIconnect copied to clipboard
PIconnect no longer automatically disconnects from the server
Bug report
Description
With commit fe138d9 the automatic disconnect from the server at exiting the context manager was disabled. This means connections to the database remain open until the python session ends, or the SDK's grace. This issue serves as a request for comments on how to fix this more efficiently.
To Reproduce
Running this snippet:
import PIconnect as PI
with PI.PIAFDatabase() as db:
print(db.server.IsConnected)
print(db.server.IsConnected)
prints:
True
True
Expected behavior
The expected result would be
True
False
Possible solutions
The problem is that PIconnect.PIAF.PIAFDatabase.__exit__
no longer calls self.server.Disconnect
. This was done intentionally to fix unexpected disconnects, but the current fix might not be the most efficient solution.
System
- OS: Windows
- Python version: Python 3.7
- PIconnect version: Hugovdberg/PIconnect@develop
Additional context
Add any other context about the problem here.
The current solution was chosen based on this post: https://pisquare.osisoft.com/thread/12398#comment-61955
I guess I have a bug related to this issue. From time to time I get this System.InvalidOperationException when I access the database in a loop. And the system does not recover from it. How to fix it?
with PI.PIAFDatabase(server="XXX", database="Production") as database:
while(True):
try:
element = database.descendant(path_to_element)
break
except:
'''
System.InvalidOperationException:
Database 'Production' has been disconnected.
This is caused by using an object from a database
after calling PISystem.Disconnect.
'''
time.sleep(60.0)
continue
#
# do other stuff
If you do the loop within the with
block, the python package should not try to disconnect. I think this fix is currently only in the development version and not yet in the Pypi version. You can work around this for now by changing your code to the following:
database = PI.PIAFDatabase(server="XXX", database="Production")
while(True):
try:
element = database.descendant(path_to_element)
break
except:
'''
System.InvalidOperationException:
Database 'Production' has been disconnected.
This is caused by using an object from a database
after calling PISystem.Disconnect.
'''
time.sleep(60.0)
continue
#
# do other stuff
The SDK should handle connecting and disconnecting automatically.