reinitiate connection on websocket error resolves issue #15
This commit is contained in:
parent
6092607207
commit
b77e105d5c
1 changed files with 17 additions and 10 deletions
|
@ -13,8 +13,10 @@ from database import db_session, init_db
|
|||
from sqlalchemy import and_
|
||||
from models import Karma, Optout, Queue, Preferences, MdnpRequests
|
||||
|
||||
_startup = threading.Event()
|
||||
_shutdown = threading.Event()
|
||||
_connected = threading.Event()
|
||||
_error = threading.Event()
|
||||
|
||||
def subscribe(connection_id):
|
||||
url = f"https://api.pnut.io/v0/channels/{config['CHANNEL']}/messages"
|
||||
|
@ -23,7 +25,9 @@ def subscribe(connection_id):
|
|||
r = requests.get(url, headers=headers)
|
||||
if r.status_code == 200:
|
||||
_connected.set()
|
||||
send(config['CHANNEL'], "Partybot online and ready! \o/")
|
||||
if _startup.isSet():
|
||||
send(config['CHANNEL'], "Partybot online and ready! \o/")
|
||||
_startup.clear()
|
||||
else:
|
||||
logger.error(r)
|
||||
|
||||
|
@ -282,7 +286,8 @@ def on_message(ws, message):
|
|||
msg = json.loads(message)
|
||||
|
||||
if not _connected.isSet() and 'connection_id' in msg['meta']:
|
||||
send(config['CHANNEL'], "...connecting circuits...")
|
||||
if _startup.isSet():
|
||||
send(config['CHANNEL'], "...connecting circuits...")
|
||||
logger.debug("connection_id: " + msg['meta']['connection_id'])
|
||||
subscribe(msg['meta']['connection_id'])
|
||||
return
|
||||
|
@ -317,26 +322,24 @@ def on_message(ws, message):
|
|||
def on_error(ws, error):
|
||||
logger.error("on_error: !!! ERROR !!!")
|
||||
logger.error(error)
|
||||
# _shutdown.set()
|
||||
_error.set()
|
||||
|
||||
def on_close(ws):
|
||||
send(config['CHANNEL'], "...shutdown initiated...")
|
||||
# send(config['CHANNEL'], "...shutdown initiated...")
|
||||
logger.debug("on_close: ### CLOSED ###")
|
||||
# _shutdown.set()
|
||||
_connected.clear()
|
||||
|
||||
def on_open(ws):
|
||||
|
||||
def run(*args):
|
||||
while not _shutdown.isSet():
|
||||
while not _error.isSet():
|
||||
qmsg = Queue.query.one_or_none()
|
||||
if qmsg:
|
||||
send(config['CHANNEL'], qmsg.msg)
|
||||
db_session.delete(qmsg)
|
||||
db_session.commit()
|
||||
time.sleep(3)
|
||||
ws.send(".")
|
||||
time.sleep(1)
|
||||
ws.close()
|
||||
time.sleep(3)
|
||||
logger.debug("*** terminate ***")
|
||||
|
||||
t = threading.Thread(target=run)
|
||||
|
@ -361,4 +364,8 @@ if __name__ == "__main__":
|
|||
ws = websocket.WebSocketApp(ws_url, on_message=on_message,
|
||||
on_error=on_error, on_close=on_close)
|
||||
ws.on_open = on_open
|
||||
ws.run_forever()
|
||||
r = True
|
||||
_startup.set()
|
||||
while r:
|
||||
_error.clear()
|
||||
r = ws.run_forever()
|
||||
|
|
Loading…
Reference in a new issue