import asyncio
import websockets
import json

async def handler(websocket, path):
    print(f"Новое подключение на путь: {path}")
    try:
        async for message in websocket:
            print(f"Получено от {path}: {message}")
            data = json.loads(message)
            message = json.dumps(data,  ensure_ascii=False)

#            if data["count_message"] == 3 or data["count_message"] == 7:
#                for i in range(2):
#                    data["count_message"] = data["count_message"] + 1
#                    message = json.dumps(data, ensure_ascii=False)
#                    await websocket.send(message)
#            elif data["count_message"] == 6:
#                continue

            data["count_message"] = data["count_message"] + 1
            data["orm_peer"] = "orm.local"
            data["orm_version"] = "2.1"
            data["orm_opc_client_peer"] = "opc.orm.local"
            if data["status"] == "init_INIT_AAA":
                data["status"] = "init_OK_AAA"
            elif data["status"] == "init_INIT_LOCATION":
                data["status"] = "init_OK_LOCATION"
            elif data["status"] == "init_INIT_CHAIN":
                data["status"] = "init_OK_CHAIN"
            message = json.dumps(data, ensure_ascii=False)
            print(f"Отправлено на {path}: {message}")
            await websocket.send(message)
    except websockets.ConnectionClosed:
        print(f"Подключение на {path} закрыто")



async def main():
    async with websockets.serve(handler, "localhost", 8080):
        print("WebSocket сервер запущен на ws://localhost:8080/")
        await asyncio.Future()

if __name__ == "__main__":
    asyncio.run(main())
