Skip to content

Commit

Permalink
Do not raise when SSE connection fails.
Browse files Browse the repository at this point in the history
This way, an exception happening during reconnect will
not make the listener die but instead make it silently
retry every second.

This is an attempt to fix #3
  • Loading branch information
DavidMStraub committed Jan 6, 2020
1 parent 9039e7d commit 244062e
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 13 deletions.
16 changes: 4 additions & 12 deletions homeconnect/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,17 +209,7 @@ def __repr__(self):
def listen_events(self, callback=None):
"""Spawn a thread with an event listener that updates the status."""
uri = f"{self.hc.host}/api/homeappliances/{self.haId}/events"
from requests.exceptions import HTTPError

sse = None
while True:
try:
sse = SSEClient(uri, session=self.hc._oauth, retry=100)
except HTTPError:
print("HTTPError while trying to listen")
time.sleep(0.1)
continue
break
sse = SSEClient(uri, session=self.hc._oauth, retry=1000)
Thread(target=self._listen, args=(sse, callback)).start()

def _listen(self, sse, callback=None):
Expand All @@ -242,7 +232,9 @@ def handle_event(self, event, callback=None):
Updates the status with the event data and executes any callback
function."""
event = json.loads(event.data)
self.status.update(self.json2dict(event["items"]))
d = self.json2dict(event["items"])
print("raw: ", event)
self.status.update(d)
if callback is not None:
callback(self)

Expand Down
6 changes: 5 additions & 1 deletion homeconnect/sseclient.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import requests
import http

from requests.exceptions import HTTPError

# Technically, we should support streams that mix line endings. This regex,
# however, assumes that a system will provide consistent line endings.
Expand Down Expand Up @@ -52,7 +53,10 @@ def _connect(self):

# TODO: Ensure we're handling redirects. Might also stick the 'origin'
# attribute on Events like the Javascript spec requires.
self.resp.raise_for_status()
try:
self.resp.raise_for_status()
except HTTPError:
print("Failed connecting.")

def _event_complete(self):
return re.search(end_of_field, self.buf) is not None
Expand Down

0 comments on commit 244062e

Please sign in to comment.