I'm very confused by asyncio. My applications work fine separately, but when I try to combine them into one file, they fail.
I want my chess engine to run:
start_engine()I also want my
websocketsserver to run:hello()
I want to communicate with my chess engine using websockets over the lan, so I need them both running at the same time.
import asyncio
import chess
import chess.engine
import websockets
async def hello(websocket, path):
fen = await websocket.recv()
print(f"< {fen}")
response = f"Got: {fen}"
await websocket.send(response)
print(f"> {response}")
async def start_engine(engine, board):
fen = "2k1r3/pR2bp2/2p1p3/N3P1p1/1PP2n2/P4P2/7r/2K2BR1 b - - 0 28"
board = chess.Board(fen)
print(board)
with await engine.analysis(board, multipv=1) as analysis:
async for info in analysis:
try:
score = info.get("score")
pv = info.get("pv")[0]
depth = info.get("seldepth")
# I want to stream this data infinitely to the websocket client
print(score, pv, depth)
except:
continue
if info.get("seldepth", 0) > 15:
break
await engine.quit()
async def main():
engine_path = "/usr/local/bin/stockfish"
transport, engine = await chess.engine.popen_uci(engine_path)
board = chess.Board()
await start_engine(engine, board)
start_server = websockets.serve(hello, "localhost", 11111)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
asyncio.run(main())
I believe the error is in the last few lines. In this case, the websockets server runs fine, but the chess engine never runs.
I'm assuming this is because asyncio.get_event_loop().run_forever() is above asyncio.run(main())
If I comment out the asyncio run_forever() lines from the bottom, the chess engine runs fine but the websockets server does not run.
How can I have both services running?
(I'm literally using the tutorial code for both services: websockets, and the chess engine)