For a deeper look into our Elektron API, look into:

Overview |  Quickstart |  Documentation |  Downloads |  Tutorials |  Articles

question

Upvotes
Accepted
16 1 0 5

Python example to handle on_close in ERP websocket

hi there,

we are trying to use the websocket API example you are providing to the community, but we face often some disconnects, and the method on_close is getting called. Iwould like to get some help here on what to do when this happens, is there somehow an easy way to reconnect ?

Could you provide me with a python example that handles such a situation when on_close() is called, as i would like to immediately reconnect?

In my code, i try to send a new authentification request with get_sts_token() but this is crashing, we get a 'WebSocketConnectiononClosedException: Connection is already closed.'

Any help and code python is welcome

Thank you

pythontreprdp-apiapiwebsocketsrrto
icon clock
10 |1500

Up to 2 attachments (including images) can be used with a maximum of 5.0 MiB each and 10.0 MiB total.

Upvotes
Accepted
13k 32 12 18

Yes, the Python example code is only to get users started quickly with API, and cannot handle every exception scenario that an application might encounter in production.

Here is a quick change that I tried and it works for if the websocket gets disconnected. You will have to make similar change in your application and check it for errors and robustness. There are a lot of assumptions built in - like your network has recovered and target machine is available for connections:

def on_close(_):
""" Called when websocket is closed """
global web_socket_open
web_socket_open = False
print("WebSocket Closed")
time.sleep(10)
print("Restarting...")
start()

def start():
global sts_token, refresh_token, expire_time
sts_token, refresh_token, expire_time = get_sts_token(None)
if not sts_token:
sys.exit(1)

# Start websocket handshake
ws_address = "wss://{}:{}/WebSocket".format(hostname, port)
print("Connecting to WebSocket " + ws_address + " ...")
web_socket_app = websocket.WebSocketApp(ws_address, on_message=on_message,
on_error=on_error,
on_close=on_close,
subprotocols=['tr_json2'])
web_socket_app.on_open = on_open

# Event loop
wst = threading.Thread(target=web_socket_app.run_forever, kwargs={'sslopt': {'check_hostname': False}})
wst.start()

try:
while True:
# Give 30 seconds to obtain the new security token and send reissue
if int(expire_time) > 30:
time.sleep(int(expire_time) - 30)
else:
# Fail the refresh since value too small
sys.exit(1)
sts_token, refresh_token, expire_time = get_sts_token(refresh_token)
if not sts_token:
sys.exit(1)

# Update token.
if logged_in:
send_login_request(web_socket_app, sts_token, True)
except KeyboardInterrupt:
web_socket_app.close()
icon clock
10 |1500

Up to 2 attachments (including images) can be used with a maximum of 5.0 MiB each and 10.0 MiB total.

Upvotes
13k 32 12 18

Hi @Mehdi, which exact example are you using; seems like you are connecting to an EDP cloud instance. We should also focus on why the websocket is disconnecting in the first place, and then put a re-connection logic to recover from any disconnect.

icon clock
10 |1500

Up to 2 attachments (including images) can be used with a maximum of 5.0 MiB each and 10.0 MiB total.

Upvotes
16 1 0 5

Hi Gurpreet,

why is the websocket disconnecting so frequently is a mystery to me. It happened again twice over the last 15h and i raised already a ticket about this. Did the EDP cloud instance face some issues? I am still waiting for the results of this investigation.

To answer your question, I have taken the available python examples from your API documentation and tutorials, and re written my application around it.

It is a real pity that the available python code examples you are providing do not handle the on_close case properly. What should that i do in this method to automatically reconnect?

def on_close(ws):
""" Called when websocket is closed """
global web_socket_open
print("WebSocket Closed")
web_socket_open = False

icon clock
10 |1500

Up to 2 attachments (including images) can be used with a maximum of 5.0 MiB each and 10.0 MiB total.

Click below to post an Idea Post Idea