Files
Telereview/code/backend_reconnaissance/network.py
2023-03-26 23:48:17 +02:00

53 lines
1.5 KiB
Python

import requests
import asyncio
import json
import os
import threading
import websockets
from dotenv import load_dotenv
load_dotenv()
class WebsocketServer(threading.Thread):
def __init__(self, onMessage, port=os.getenv("PORT"), host=os.getenv("HOST")):
threading.Thread.__init__(self)
self.host = host
self.port = port
self.messageQueue = []
self.onMessage = onMessage
def run(self):
print("server thread started")
asyncio.run(self.runServer())
async def runServer(self):
async with websockets.serve(self.handler, self.host, self.port):
await asyncio.Future()
async def handler(self,websocket):
while True:
for msg in self.messageQueue:
# print("sending", json.dumps(msg))
await websocket.send(json.dumps(msg))
self.messageQueue.pop(0)
await asyncio.sleep(0.01)
def sendMessage(self,message):
self.messageQueue.append(message)
class ApiClient():
def __init__(self, host=os.getenv("API_HOST"), port=os.getenv("API_PORT")):
self.host = host
self.port = port
def send(self,note,note_autre):
#Exemple ajout d'un commentaire depuis la borne (site ou geste)
avis = {
"note": note,
"source": "borne",
"commentaire":"",
#Optionel
"notes_autre": '{"proprete":'+str(note_autre)+',"calme":10}',
}
return requests.post("http://"+self.host+":"+self.port+"/add_review", data=avis)