added temp fake data to the app for it to send to the JS side.

This commit is contained in:
UpstreamData
2022-03-30 08:42:21 -06:00
parent a0311e3ce3
commit eaaf137b9b
3 changed files with 327 additions and 15 deletions

View File

@@ -1,11 +1,15 @@
from fastapi import FastAPI, WebSocket, Request
from fastapi.websockets import WebSocketDisconnect
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
import websockets.exceptions
import asyncio
import uvicorn
import os
from fastapi.templating import Jinja2Templates
from tools.web_testbench import miner_network
app = FastAPI()
@@ -15,12 +19,31 @@ app.mount("/public", StaticFiles(
templates = Jinja2Templates(
directory=os.path.join(os.path.dirname(__file__), "templates"))
miner_data = {
'IP': '192.168.1.10',
'Light': 'show',
'Fans': {
'fan_0': {'RPM': 4620},
'fan_1': {'RPM': 4560},
'fan_2': {'RPM': 0},
'fan_3': {'RPM': 0}
},
'HR': {
'board_6': {'HR': 4.85},
'board_7': {'HR': 0.0},
'board_8': {'HR': 0.81}
},
'Temps': {
'board_6': {'Board': 85.6875, 'Chip': 93.0},
'board_7': {'Board': 0.0, 'Chip': 0.0},
'board_8': {'Board': 0.0, 'Chip': 0.0}
}
}
class ConnectionManager:
_instance = None
def __init__(self):
self.connections = []
_connections = []
def __new__(cls):
if not cls._instance:
@@ -32,16 +55,32 @@ class ConnectionManager:
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.connections.append(websocket)
await websocket.send_json({"miners": [str(miner) for miner in miner_network.hosts()]})
ConnectionManager._connections.append(websocket)
async def broadcast_json(self, data: str):
for connection in self.connections:
await connection.json(data)
def disconnect(self, websocket: WebSocket):
print("Disconnected")
ConnectionManager._connections.remove(websocket)
async def broadcast_json(self, data: dict):
for connection in ConnectionManager._connections:
try:
await connection.send_json(data)
except:
self.disconnect(connection)
@app.websocket("/ws")
async def ws(websocket: WebSocket):
await ConnectionManager().connect(websocket)
try:
while True:
data = await websocket.receive()
except WebSocketDisconnect:
ConnectionManager().disconnect(websocket)
except RuntimeError:
ConnectionManager().disconnect(websocket)
@app.get("/")
@@ -51,5 +90,14 @@ def dashboard(request: Request):
})
@app.on_event("startup")
def start_monitor():
asyncio.create_task(monitor())
async def monitor():
while True:
await ConnectionManager().broadcast_json(miner_data)
await asyncio.sleep(5)
if __name__ == '__main__':
uvicorn.run("app:app", host="0.0.0.0", port=80)