More robust reconnection logic for Pushbullet backend

This commit is contained in:
Fabio Manganiello 2021-05-19 18:43:44 +02:00
parent a39452124d
commit d35a9729a4
2 changed files with 60 additions and 6 deletions

View file

@ -43,6 +43,7 @@ class PushbulletBackend(Backend):
self.pb_device_id = None
self.pb = None
self.listener = None
self._retrying = False
def _initialize(self):
# noinspection PyPackageRequirements
@ -132,16 +133,32 @@ class PushbulletBackend(Backend):
self.close()
self.logger.info('Pushbullet backend terminated')
def on_error(self, e):
self.logger.exception(e)
self.close()
self.run_listener()
def on_error(self, err=None):
if err:
self.logger.exception(err)
try:
self.close()
except Exception as e:
self.logger.warning(f'close() error: {e}')
if not self._retrying:
time.sleep(5)
self.logger.info('Retrying connection')
self._retrying = True
self.run_listener()
def on_open(self):
self.logger.info('Pushbullet service connected')
self._retrying = False
def run_listener(self):
from pushbullet import Listener
from .listener import Listener
self.logger.info('Initializing Pushbullet backend - device_id: {}'.format(self.device_name))
self.listener = Listener(account=self.pb, on_push=self.on_push(), on_error=self.on_error,
self.listener = Listener(account=self.pb, on_push=self.on_push(),
on_open=self.on_open,
on_close=self.on_error,
on_error=self.on_error,
http_proxy_host=self.proxy_host,
http_proxy_port=self.proxy_port)

View file

@ -0,0 +1,37 @@
from typing import Callable, Optional
from pushbullet import Listener as _Listener
class Listener(_Listener):
"""
Extends the Pushbullet Listener object by adding ``on_open`` and ``on_close`` handlers.
"""
def __init__(self,
*args,
on_open: Optional[Callable[[], None]] = None,
on_close: Optional[Callable[[], None]] = None,
**kwargs):
super().__init__(*args, **kwargs)
self._on_open_hndl = on_open
self._on_close_hndl = on_close
def _on_open(self):
def callback(*_):
self.connected = True
self.last_update = time.time()
if self._on_open_hndl:
self._on_open_hndl()
return callback
def _on_close(self):
def callback(*_):
self.connected = False
if self._on_close_hndl:
self._on_close_hndl()
return callback
# vim:sw=4:ts=4:et: