Skip to content

Commit

Permalink
Use threading.Event() and fix exception on TV exit
Browse files Browse the repository at this point in the history
  • Loading branch information
trevorbayless committed Jun 21, 2024
1 parent cfaf8fa commit 931348e
Showing 1 changed file with 8 additions and 10 deletions.
18 changes: 8 additions & 10 deletions src/cli_chess/core/game/online_game/watch_tv/watch_tv_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,9 @@ class StreamTVChannel(threading.Thread):
def __init__(self, channel: TVChannelMenuOptions):
super().__init__(daemon=True)
self.channel = channel
self.running = False
self.max_retries = 10
self.retries = 0
self._stopped = threading.Event()
self.e_tv_stream_event = Event()

try:
Expand All @@ -102,20 +102,18 @@ def __init__(self, channel: TVChannelMenuOptions):
def run(self):
"""Main entrypoint for the thread"""
log.info(f"Started watching {self.channel.value} TV")
self.running = True
while self.running:
while not self._stopped.is_set():
try:
self.e_tv_stream_event.notify(EventTopics.GAME_SEARCH)

# TODO: Update to use berserk TV specific method once implemented
stream = self.api_client.tv._r.get(f"/api/tv/{self.channel.key}/feed", stream=True) # noqa

for event in stream:
# TODO: This does close the stream, but not until the next event comes in (which can be a while
# sometimes (especially in longer time format games like Classical). Ideally there's
# a way to immediately kill the stream, without waiting for another event.
if not self.running:
stream.close()
if self._stopped.is_set():
# TODO: This does close the stream, but not until the next event comes in (which can be a while
# sometimes (especially in longer time format games like Classical). Ideally there's
# a way to immediately kill the stream, without waiting for another event.
break

t = event.get('t')
Expand All @@ -134,7 +132,7 @@ def run(self):
self.handle_exceptions(e)

else:
if self.running:
if not self._stopped.is_set():
self.retries = 0
log.debug("Sleeping 2 seconds before finding next TV game")
sleep(2)
Expand All @@ -159,5 +157,5 @@ def handle_exceptions(self, e: Exception):

def stop_watching(self):
log.info("Stopping TV stream")
self._stopped.set()
self.e_tv_stream_event.remove_all_listeners()
self.running = False

0 comments on commit 931348e

Please sign in to comment.