Skip to content

Free Motion Capture for Everyone πŸ’€βœ¨

TypeScript

create pub/sub for working camera frames

Endurance Idehen08d85d28c2a9
diff --git a/bin/build.sh b/bin/linux/build.sh
similarity index 100%
rename from bin/build.sh
rename to bin/linux/build.sh
diff --git a/bin/run_uvicorn_server.sh b/bin/linux/run_uvicorn_server.sh
similarity index 73%
rename from bin/run_uvicorn_server.sh
rename to bin/linux/run_uvicorn_server.sh
index 2290cd31..38df6ab4 100755
--- a/bin/run_uvicorn_server.sh
+++ b/bin/linux/run_uvicorn_server.sh
@@ -3,5 +3,5 @@
# Start the webserver
-uvicorn --factory src.api.app_factory:create_app --port 8080 --host 0.0.0.0 --reload
+uvicorn --factory src.api.app_factory:create_app --port 8080 --host 0.0.0.0 --workers 4 --ws websockets
diff --git a/bin/linux/run_web_server.sh b/bin/linux/run_web_server.sh
new file mode 100755
index 00000000..6c7a2f5a
--- /dev/null
+++ b/bin/linux/run_web_server.sh
@@ -0,0 +1,8 @@
+#!/usr/bin/env bash
+#
+# Start the webserver
+
+# shellcheck disable=SC2086
+#gunicorn -b 0.0.0.0:8080 --timeout 0 -w 1 -k uvicorn.workers.UvicornWorker 'src.api.app_factory:create_app()'
+#hypercorn 'src.api.app_factory:create_app()' --bind 0.0.0.0:8080 --websocket-ping-interval 1000
+uvicorn --factory src.api.app_factory:create_app --port 8080 --host 0.0.0.0 --workers 4
diff --git a/bin/shell.sh b/bin/linux/shell.sh
similarity index 100%
rename from bin/shell.sh
rename to bin/linux/shell.sh
diff --git a/bin/test.sh b/bin/linux/test.sh
similarity index 100%
rename from bin/test.sh
rename to bin/linux/test.sh
diff --git a/bin/up.sh b/bin/linux/up.sh
similarity index 100%
rename from bin/up.sh
rename to bin/linux/up.sh
diff --git a/bin/run_web_server.sh b/bin/run_web_server.sh
deleted file mode 100755
index 6601863b..00000000
--- a/bin/run_web_server.sh
+++ /dev/null
@@ -1,6 +0,0 @@
-#!/usr/bin/env bash
-#
-# Start the webserver
-
-# shellcheck disable=SC2086
-gunicorn -b 0.0.0.0:8080 --timeout 0 -w 1 -k uvicorn.workers.UvicornWorker 'src.api.app_factory:create_app()'
\ No newline at end of file
diff --git a/bin/windows/run_web_server.bat b/bin/windows/run_web_server.bat
new file mode 100644
index 00000000..84c654bd
--- /dev/null
+++ b/bin/windows/run_web_server.bat
@@ -0,0 +1 @@
+uvicorn --factory src.api.app_factory:create_app --port 8080 --host 0.0.0.0 --workers 4
\ No newline at end of file
diff --git a/freemocap-ui/src/views/PythonToJsTest.tsx b/freemocap-ui/src/views/PythonToJsTest.tsx
index 41ed1da3..34dae6b6 100644
--- a/freemocap-ui/src/views/PythonToJsTest.tsx
+++ b/freemocap-ui/src/views/PythonToJsTest.tsx
@@ -36,7 +36,9 @@ export const PythonToJsTest = () => {
<Box>
{
keys.map(k => {
- return <img src={`data:image/png;base64,${data[k]}`}/>
+ return (
+ <img src={`data:image/png;base64,${data[k]}`} alt={"video capture"}/>
+ )
})
}
</Box>
diff --git a/freemocap/prod/cam/detection/cam_detection.py b/freemocap/prod/cam/detection/cam_detection.py
index d77f8f65..a0e125dd 100644
--- a/freemocap/prod/cam/detection/cam_detection.py
+++ b/freemocap/prod/cam/detection/cam_detection.py
@@ -20,12 +20,10 @@ class DetectPossibleCameras:
cap = cv2.VideoCapture(camNum, cv2_backend)
success, image = cap.read()
if success:
- logger.info(f"We found one: {camNum}")
try:
cams_to_use_list.append(RawCamera(
port_number=camNum,
))
- logger.info(cap.get(cv2.CAP_PROP_SETTINGS))
finally:
cap.release()
diff --git a/freemocap/prod/cam/detection/dto.py b/freemocap/prod/cam/detection/dto.py
index ff9239d6..1e4cca48 100644
--- a/freemocap/prod/cam/detection/dto.py
+++ b/freemocap/prod/cam/detection/dto.py
@@ -3,7 +3,7 @@ from pydantic import BaseModel
class RawCamera(BaseModel):
- port_number: int
+ port_number: str
class FindAvailableResponse(BaseModel):
diff --git a/requirements.txt b/requirements.txt
index 863f7435..be640f47 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -19,4 +19,8 @@ gunicorn==20.1.0
requests==2.27.1
pyudev==0.22.0
python-multipart==0.0.5
-websockets==10.1
\ No newline at end of file
+websockets==10.1
+sqlalchemy==1.4.31
+singleton-decorator==1.0.0
+
+# Requirements for core-processor
diff --git a/src/api/app_factory.py b/src/api/app_factory.py
index 6b90261e..b3fa9d55 100644
--- a/src/api/app_factory.py
+++ b/src/api/app_factory.py
@@ -5,7 +5,7 @@ from src.api.middleware.cors import cors
from src.api.routes import enabled_routers
-def create_app():
+def create_app(*args, **kwargs):
_app = FastAPI()
cors(_app)
diff --git a/src/api/routes/camera/cam_data_ws.py b/src/api/routes/camera/cam_data_ws.py
index d745d49c..0bea91b4 100644
--- a/src/api/routes/camera/cam_data_ws.py
+++ b/src/api/routes/camera/cam_data_ws.py
@@ -15,6 +15,7 @@ async def websocket_endpoint(websocket: WebSocket, webcam_id: str):
await websocket.accept()
cam = OpenCVCamera(port_number=webcam_id)
cam.connect()
+
try:
while True:
success, image, timestamp = cam.get_next_frame()
diff --git a/src/core_processor/app_events/app_queue.py b/src/core_processor/app_events/app_queue.py
new file mode 100644
index 00000000..29a2e73c
--- /dev/null
+++ b/src/core_processor/app_events/app_queue.py
@@ -0,0 +1,23 @@
+from asyncio import Queue
+
+from singleton_decorator import singleton
+
+
+@singleton
+class AppQueue:
+ _queues = {
+ "0": {
+ "queue": Queue()
+ }
+ }
+
+ def create(self, webcam_id):
+ if webcam_id not in self._queues:
+ self._queues[webcam_id] = {"queue": Queue()}
+
+ def get_by_webcam_id(self, webcam_id) -> Queue:
+ return self._queues[webcam_id]["queue"]
+
+
+def create_or_get_queue():
+ pass
diff --git a/src/core_processor/app_events/event_notify.py b/src/core_processor/app_events/event_notify.py
new file mode 100644
index 00000000..53ce5e4d
--- /dev/null
+++ b/src/core_processor/app_events/event_notify.py
@@ -0,0 +1,31 @@
+import logging
+
+from src.core_processor.app_events.app_queue import AppQueue
+from src.core_processor.subscribers.subscribers import subscribers
+
+logger = logging.getLogger(__name__)
+
+
+class EventNotifier:
+
+ def __init__(self, webcam_ids):
+ self._app_queues = AppQueue()
+ self._workers = []
+ self._webcam_ids = webcam_ids
+ self._construct()
+
+ def _construct(self):
+ self._workers = [sub() for sub in subscribers]
+
+ async def notify_all_subscribers(self):
+ while True:
+ for webcam_id in self._webcam_ids:
+ queue = self._app_queues.get_by_webcam_id(webcam_id)
+ try:
+ message = await queue.get()
+ queue.task_done()
+ for worker in self._workers:
+ worker.process(message)
+ except Exception as e:
+ logger.error(e)
+ logger.error("Notifier dead")
diff --git a/src/core_processor/board_detection/detect.py b/src/core_processor/board_detection/detect.py
new file mode 100644
index 00000000..c6f3889e
--- /dev/null
+++ b/src/core_processor/board_detection/detect.py
@@ -0,0 +1,9 @@
+
+
+class BoardDetection:
+
+ def __init__(self):
+ pass
+
+ def process(self, *args, **kwargs):
+ pass
\ No newline at end of file
diff --git a/src/core_processor/log_setup.py b/src/core_processor/log_setup.py
new file mode 100644
index 00000000..23f7b3ff
--- /dev/null
+++ b/src/core_processor/log_setup.py
@@ -0,0 +1,5 @@
+import logging
+
+
+def logging_setup():
+ logging.getLogger("websockets.client").setLevel(level=logging.INFO)
diff --git a/src/core_processor/main.py b/src/core_processor/main.py
new file mode 100644
index 00000000..c155e544
--- /dev/null
+++ b/src/core_processor/main.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env python
+
+import asyncio
+from typing import List, Optional
+
+from freemocap.prod.cam.detection.cam_detection import DetectPossibleCameras
+from src.core_processor.app_events.event_notify import EventNotifier
+from src.core_processor.log_setup import logging_setup
+from src.core_processor.ws_connection import WSConnection
+
+loop = asyncio.get_event_loop()
+
+
+async def begin_webcam_capture(webcam_ids: Optional[List[str]] = None):
+ if not webcam_ids:
+ cams = DetectPossibleCameras().find_available_cameras().cams_to_use
+ webcam_ids = [cam.port_number for cam in cams]
+
+ main_conn = WSConnection()
+ tasks = [
+ loop.create_task(main_conn.connect(wb_id))
+ for wb_id in webcam_ids
+ ]
+
+ notify_coroutine = EventNotifier(webcam_ids).notify_all_subscribers()
+ tasks.append(
+ loop.create_task(notify_coroutine)
+ )
+
+ await asyncio.wait_for(
+ asyncio.gather(*tasks),
+ timeout=None,
+ )
+
+
+if __name__ == "__main__":
+ logging_setup()
+ loop.run_until_complete(begin_webcam_capture())
diff --git a/src/core_processor/subscribers/subscribers.py b/src/core_processor/subscribers/subscribers.py
new file mode 100644
index 00000000..277ae6c8
--- /dev/null
+++ b/src/core_processor/subscribers/subscribers.py
@@ -0,0 +1,3 @@
+from src.core_processor.board_detection.detect import BoardDetection
+
+subscribers = [BoardDetection]
\ No newline at end of file
diff --git a/src/core_processor/ws_connection.py b/src/core_processor/ws_connection.py
new file mode 100644
index 00000000..012db03f
--- /dev/null
+++ b/src/core_processor/ws_connection.py
@@ -0,0 +1,27 @@
+import logging
+
+import websockets
+
+from src.core_processor.app_events.app_queue import AppQueue
+
+logger = logging.getLogger(__name__)
+
+
+class WSConnection:
+
+ _host = "ws://localhost:8080/ws"
+
+ async def connect(self, webcam_id: str):
+ # TODO: Spawn new process to perform this job?
+ uri = f"{self._host}/{webcam_id}"
+ app = AppQueue()
+ app.create(webcam_id)
+ queue = app.get_by_webcam_id(webcam_id)
+ async for websocket in websockets.connect(uri, max_size=None, ping_timeout=None):
+ try:
+ async for message in websocket:
+ await queue.put(message)
+ print(f"webcam_id: {webcam_id}, msg rcv")
+ except websockets.ConnectionClosed as e:
+ logger.error(e)
+ continue