From d35a9729a47da128e17c1f6e3e586926ae6aba7b Mon Sep 17 00:00:00 2001 From: Fabio Manganiello Date: Wed, 19 May 2021 18:43:44 +0200 Subject: [PATCH] More robust reconnection logic for Pushbullet backend --- platypush/backend/pushbullet/__init__.py | 29 +++++++++++++++---- platypush/backend/pushbullet/listener.py | 37 ++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 6 deletions(-) create mode 100644 platypush/backend/pushbullet/listener.py diff --git a/platypush/backend/pushbullet/__init__.py b/platypush/backend/pushbullet/__init__.py index 78a4fe31..462d48b2 100644 --- a/platypush/backend/pushbullet/__init__.py +++ b/platypush/backend/pushbullet/__init__.py @@ -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) diff --git a/platypush/backend/pushbullet/listener.py b/platypush/backend/pushbullet/listener.py new file mode 100644 index 00000000..218a5045 --- /dev/null +++ b/platypush/backend/pushbullet/listener.py @@ -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: