Non-blocking communication with engine #1061
-
Like many others I have built a reed switch chessboard (this one is big!) It has a Teensy 4.1 to do the scanning and move validation. The board accepts a FEN string and if the position matches the FEN it will allow a move to be made. I did it this way so that sliding moves, knocked over pieces, clumsy captures etc. all work. Pieces can dance around the board on their way to a destination if they like. If the move is legal it will be sent via serial to a Raspberry Pi 4b. On the Pi I have built a touchscreen GUI using PySImpleGUI. I am using python-chess (awesome) for managing the games, pgn files and FEN generation for the board. I have reached a stage where human v. human games can be played, recorded, e-mailed etc. The GUI is responsive during game play and I have smooth running clocks. Now it is time to interact with Stockfish / UCI engines. I can launch an engine and interact with it. The problem is that whilst waiting for a response from the engine my GUI / clocks stop. This is not unexpected - it was always going to hold up my main loop - that's where the code is to wait on the response. So I need to be able to send a command to the engine and then in my main loop check to see if there is a response. It is fair to say I am a Python 'newbie' and I'm struggling to understand where to start. Do I need threading, mutltprocessing, asyncio? Many people must have exactly this thing working. I have looked at the asyncio chess.engine examples, but I cannot get my head around the flow of execution and how it might be integrated into my code. Any help much appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The next best thing is to use the blocking
|
Beta Was this translation helpful? Give feedback.
asyncio
would have the lowest overhead, but it looks like PySimpleGUI does not provide integration.The next best thing is to use the blocking
chess.engine.SimpleEngine
. I found this example for how to deal with blocking operations in PySimpleGUI: https://github.com/PySimpleGUI/PySimpleGUI/blob/master/DemoPrograms/Demo_Multithreaded_Long_Tasks.py. Sowindow.start_thread()
can be used to start work that would otherwise block the main thread, and the thread will be able to send events back to the main thread.chess.engine.SimpleEngine
is thread-safe as long as objects passed to methods are not concurrently modified. So you could create one instance and use it in the background threads.