Skip to content

Commit

Permalink
enhancement(zmq): Add zmq hook WIP
Browse files Browse the repository at this point in the history
Remove asyncio code
  • Loading branch information
DarwinsBuddy committed Nov 23, 2024
1 parent 3cf3880 commit d0ed4cd
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 41 deletions.
39 changes: 7 additions & 32 deletions foosball/hooks/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import threading
from abc import ABC, abstractmethod

import asyncio


class Hook(ABC):

Expand All @@ -21,40 +18,18 @@ def stop(self, *args, **kwargs):
pass


class HookManager(threading.Thread):
def __init__(self):
super().__init__(daemon=True)
self.hooks = []
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
self.stop_event = asyncio.Event()
class HookManager:
def __init__(self, hooks=None):
self.hooks = hooks or []

def run(self):
def start(self):
for hook in self.hooks:
self.loop.call_soon_threadsafe(hook.start)
self.loop.run_until_complete(self.stop_event.wait())

def extend(self, hooks: [Hook], start=False):
self.hooks.extend(hooks)
for hook in hooks:
if start:
self.loop.call_soon_threadsafe(hook.start)

def add(self, hook: Hook, start=False):
self.hooks.append(hook)
if start:
self.loop.call_soon_threadsafe(hook.start)

def remove(self, hook: Hook):
self.loop.call_soon_threadsafe(hook.stop)
self.hooks.remove(hook)
hook.start()

def invoke(self, *args, **kwargs):
for hook in self.hooks:
self.loop.call_soon_threadsafe(hook.invoke(*args, **kwargs))
hook.invoke(*args, **kwargs)

def stop(self):
for hook in self.hooks:
self.loop.call_soon_threadsafe(hook.stop)
self.hooks = []
self.stop_event.set()
hook.stop()
14 changes: 5 additions & 9 deletions foosball/tracking/analyzer/ScoreAnalyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,14 @@ def __init__(self, dims: FrameDimensions, goal_grace_period_sec: float = 1.0, *a
self.last_track_sighting: dt.datetime | None = None
self.last_track: Optional[Track] = None
self.goal_candidate = None
self.goal_hooks = HookManager()
self.frame_hooks = HookManager()
self.zmq_hook = ZMQHook(host="localhost", port=5555, topic="ws")
# TODO: create them somewhere else and pass them down
self.goal_hooks.extend([
self.goal_hooks = HookManager([
AudioHook("goal"),
Webhook.load_webhook('goal_webhook.yaml'),
self.zmq_hook
Webhook.load_webhook('goal_webhook.yaml')
])
self.frame_hooks.extend([
self.zmq_hook
self.frame_hooks = HookManager([
ZMQHook(host="localhost", port=5555, topic="ws")
])
# TODO: create them somewhere else and pass them down
self.goal_hooks.start()
self.frame_hooks.start()

Expand Down

0 comments on commit d0ed4cd

Please sign in to comment.