import asyncio
import websockets
import threading
import time
import json

connected = set()

async def echo(websocket, path):
    connected.add(websocket)
    try:
        async for message in websocket:
            print(message)
            try:
                message1 = json.loads(message)
                if (message1['nereye']=="outespc"):
                    responseMessage = json.dumps(message1)
                    for ws in connected:
                        await ws.send(responseMessage)
            except:
                pass
    finally:
        connected.remove(websocket)

def run_server():
    asyncio.set_event_loop(asyncio.new_event_loop())
    asyncio.get_event_loop().run_until_complete(websockets.serve(echo, "0.0.0.0", 5001))
    asyncio.get_event_loop().run_forever()

async def run_client():
    uri = "ws://127.0.0.1:5001"
    tetik=1
    say=1
    start_time = time.time()
    while True:
        
        current_time = time.time()
        if current_time - start_time >= 2:
            
            async with websockets.connect(uri) as websocket:
                #await websocket.send("Hello, WebSocket!")
                responseJson = {"nereye":"outespc","cihaz_id":"1001","out": f"out{say+1}","out_value":tetik,"gecikme":0}
                responseMessage = json.dumps(responseJson)
                await websocket.send(responseMessage)
                #response = await websocket.recv()
                #print(f"Received response from server: {response}")
            
            say+=1
            start_time = current_time
            if say>3:
                say=0
                if tetik==0:
                    tetik=1
                else:
                    tetik=0

if __name__ == "__main__":
    server_thread = threading.Thread(target=run_server)
    server_thread.start()

    asyncio.run(run_client())
