34 lines
808 B
Python
34 lines
808 B
Python
import asyncio
|
|
|
|
from tinydb import TinyDB
|
|
|
|
from settings import settings
|
|
|
|
db = TinyDB(settings.database_path)
|
|
computers = db.table("computers")
|
|
|
|
|
|
class StateManager:
|
|
def __init__(self):
|
|
self.websockets = set()
|
|
|
|
self.current_state = None
|
|
self.update_state()
|
|
|
|
def update_state(self):
|
|
self.current_state = {"computers": computers.all()}
|
|
|
|
async def push_state(self, socket):
|
|
await socket.send_json(self.current_state)
|
|
|
|
async def on_connect(self, socket):
|
|
self.websockets.add(socket)
|
|
await self.push_state(socket)
|
|
|
|
async def on_disconnect(self, socket):
|
|
self.websockets.remove(socket)
|
|
|
|
async def on_change(self):
|
|
self.update_state()
|
|
await asyncio.gather(self.push_state(socket) for socket in self.websockets)
|