Add pult frontend stuff

This commit is contained in:
2022-02-19 11:47:50 +01:00
parent 763aa23ca8
commit 62636fa2f9
15 changed files with 29069 additions and 0 deletions

153
pult/backend/.gitignore vendored Normal file
View File

@@ -0,0 +1,153 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

1
pult/backend/frontend Symbolic link
View File

@@ -0,0 +1 @@
../frontend/build

162
pult/backend/main.py Normal file
View File

@@ -0,0 +1,162 @@
import asyncio
from typing import *
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from pydantic import BaseModel, Field, ValidationError
app = FastAPI()
class Slider:
def __init__(self):
self.value = 0
self.owner: Optional[WebSocket] = None
self.release_timer: Optional[asyncio.Task] = None
self.release_event = asyncio.Event()
def cancel_release_timer(self):
if self.release_timer is not None:
self.release_timer.cancel()
self.release_timer = None
def reset_release_timer(self):
self.cancel_release_timer()
self.release_timer = asyncio.create_task(self._release_timer())
async def _release_timer(self):
await asyncio.sleep(1)
self.release_event.set()
dmx_state = [Slider() for _ in range(8)]
class GrabAction(BaseModel):
action_type: Literal["grab"]
slider: int
class ReleaseAction(BaseModel):
action_type: Literal["release"]
slider: int
class MoveAction(BaseModel):
action_type: Literal["move"]
slider: int
new_value: int
class ClientAction(BaseModel):
action: Union[GrabAction, ReleaseAction, MoveAction] = Field(
..., discriminator="action_type"
)
class SocketManager:
def __init__(self):
self.sockets = set()
async def on_connect(self, ws: WebSocket):
self.sockets.add(ws)
await self.push_state(ws)
def on_disconnect(self, ws: WebSocket):
self.sockets.remove(ws)
for slider in dmx_state:
if slider.owner == ws:
slider.owner = None
async def on_action(
self, ws: WebSocket, action: Union[GrabAction, ReleaseAction, MoveAction]
):
slider = dmx_state[action.slider]
if action.action_type == "grab":
print(f"grab {action.slider}")
if slider.owner is None:
slider.owner = ws
slider.reset_release_timer()
elif action.action_type == "release":
print(f"release {action.slider}")
if slider.owner == ws:
slider.owner = None
slider.cancel_release_timer()
elif action.action_type == "move":
print(f"move {action.slider} -> {action.new_value}")
if slider.owner == ws:
slider.value = action.new_value
slider.reset_release_timer()
await self.push_all()
async def push_state(self, ws: WebSocket):
response = []
for slider in dmx_state:
value = slider.value
if slider.owner == ws:
status = "owned"
elif slider.owner is not None:
status = "locked"
else:
status = "open"
response.append({"value": value, "status": status})
await ws.send_json(response)
async def push_all(self):
await asyncio.gather(*[self.push_state(ws) for ws in self.sockets])
async def watch_auto_release(self):
async def _watch(slider):
while True:
await slider.release_event.wait()
print("resetteroni")
slider.release_event.clear()
slider.owner = slider.release_timer = None
await self.push_all()
await asyncio.gather(*[_watch(slider) for slider in dmx_state])
socket_manager = SocketManager()
@app.websocket("/ws")
async def ws_handler(ws: WebSocket):
await ws.accept()
await socket_manager.on_connect(ws)
try:
while True:
data = await ws.receive_json()
try:
action = ClientAction.parse_obj(data)
await socket_manager.on_action(ws, action.action)
except ValidationError as e:
print(e)
except WebSocketDisconnect as e:
pass
finally:
socket_manager.on_disconnect(ws)
app.mount("/", StaticFiles(directory="frontend", html=True))
@app.on_event("startup")
async def on_startup():
asyncio.create_task(socket_manager.watch_auto_release())

View File

@@ -0,0 +1,11 @@
anyio==3.5.0
asgiref==3.5.0
click==8.0.3
fastapi==0.73.0
h11==0.13.0
idna==3.3
pydantic==1.9.0
sniffio==1.2.0
starlette==0.17.1
typing-extensions==4.1.1
uvicorn==0.17.5