UCILoader 1.1.2
Small C++ library that allows user to connect to a chess engines via UCI protocol.
Loading...
Searching...
No Matches
UCILoader::EngineInstance< Move > Class Template Reference

Top-level interface for managing and interacting with a UCI chess engine. More...

#include <EngineConnection.h>

Inheritance diagram for UCILoader::EngineInstance< Move >:
UCILoader::EventEmitter

Classes

class  EngineBusyException
 Exception thrown when attempting to start a search while one is already in progress. More...
 
class  TimeoutException
 Exception thrown when a sync() or ping() operation times out. More...
 

Public Member Functions

 EngineInstance (std::shared_ptr< ProcessWrapper > engineProcess, std::shared_ptr< Marschaler< Move > > moveMarshaler, std::shared_ptr< PatternMatcher > moveValidator, std::unique_ptr< Logger > &&logger)
 
void sync (std::chrono::milliseconds timeout=std::chrono::milliseconds(10000))
 Synchronize engine state with local representation.
 
void ucinewgame ()
 Send the ucinewgame command to the engine.
 
std::chrono::milliseconds ping (std::chrono::milliseconds timeout=std::chrono::milliseconds(10000))
 Measure engine latency by performing a ping operation.
 
std::shared_ptr< SearchConnection< Move > > getCurrentSearch ()
 Get the currently active search connection.
 
std::shared_ptr< SearchConnection< Move > > search (const GoParams< Move > &params, const PositionFormatter &pos, const std::vector< Move > moves={})
 Start a new search operation with specified parameters.
 
std::string getName ()
 Get the engine's name as declared via the id name command.
 
std::string getAuthor ()
 Get the engine author's name as declared via the id author command.
 
bool healthCheck ()
 Check the health status of the underlying engine process.
 
void quit ()
 Manually terminate the engine process.
 
- Public Member Functions inherited from UCILoader::EventEmitter
void unlink (const EventReceiver *receiver)
 Disconnect a specific receiver from future events.
 
void connect (std::shared_ptr< EventReceiver > receiver)
 Connect a custom event receiver.
 
void connect (std::function< void(const EngineEvent *)> callback, uint32_t eventFilter)
 Connect a callback function that receives the full event.
 
void connect (std::function< void()> callback, uint32_t eventFilter)
 Connect a simple parameterless callback function.
 

Public Attributes

EngineOptionsMap options
 Map of available engine options.
 

Additional Inherited Members

- Protected Member Functions inherited from UCILoader::EventEmitter
virtual ~EventEmitter ()
 Virtual destructor ensuring proper cleanup.
 
void emit (const EngineEvent *event)
 Emit an event to all connected receivers.
 

Detailed Description

template<class Move>
class UCILoader::EngineInstance< Move >

Top-level interface for managing and interacting with a UCI chess engine.

Template Parameters
MoveThe move type used by the engine

EngineInstance is the primary interface for communicating with a chess engine over UCI protocol. It handles:

  • Engine initialization and synchronization
  • Option management and configuration
  • Search operations and result retrieval
  • Event emission for status changes
  • Graceful shutdown

Typical Usage:

// Create engine instance with logging
auto engine = builder.build(process, Loggers::toFile("debug.log") | LoggerTraits::Pretty);
// Synchronize to load options and metadata
engine->sync();
// Query engine info
std::cout << "Engine: " << engine->getName() << std::endl;
// Configure options
if (engine->options.contains("Hash")) {
engine->options["Hash"] = 256;
}
// Start search
auto search = engine->search(params, position, moves);
search->waitFor(std::chrono::seconds(5));
if (search->getStatus() == ResultReady) {
auto result = search->getResult();
std::cout << "Best move: " << moveToString(result.bestMove) << std::endl;
}
std::shared_ptr< SearchConnection< Move > > search(const GoParams< Move > &params, const PositionFormatter &pos, const std::vector< Move > moves={})
Start a new search operation with specified parameters.
Definition: EngineConnection.h:995
const LoggerTrait & Pretty
Trait that formats log messages for human readability.
Definition: Logger.cpp:165
LoggerBuilder toFile(const std::string &filename)
Create a logger that outputs to a file.
Definition: Logger.cpp:185
Warning
Always call sync() after construction to ensure engine options and metadata are loaded.
See also
EngineInstanceBuilder for creating instances
Logger for configuring logging behavior

Member Function Documentation

◆ getAuthor()

template<class Move >
std::string UCILoader::EngineInstance< Move >::getAuthor
inline

Get the engine author's name as declared via the id author command.

Returns
The author name, or "<empty>" if not provided by the engine

It's recommended to call sync() before querying this to ensure the author name has been received and loaded.

◆ getCurrentSearch()

template<class Move >
std::shared_ptr< SearchConnection< Move > > UCILoader::EngineInstance< Move >::getCurrentSearch
inline

Get the currently active search connection.

Returns
Shared pointer to the current SearchConnection, or nullptr if no search is in progress

◆ getName()

template<class Move >
std::string UCILoader::EngineInstance< Move >::getName
inline

Get the engine's name as declared via the id name command.

Returns
The engine name, or "<empty>" if not provided by the engine

It's recommended to call sync() before querying this to ensure the engine name has been received and loaded.

◆ healthCheck()

template<class Move >
bool UCILoader::EngineInstance< Move >::healthCheck
inline

Check the health status of the underlying engine process.

Returns
True if the engine process is alive and responsive, false if it has been terminated

If this method returns false, the EngineInstance is in an unstable state and should not be used further.

◆ ping()

template<class Move >
std::chrono::milliseconds UCILoader::EngineInstance< Move >::ping ( std::chrono::milliseconds  timeout = std::chrono::milliseconds(10000))
inline

Measure engine latency by performing a ping operation.

This is a convenience wrapper around sync() that measures the round-trip time.

Parameters
timeoutMaximum time to wait for engine response (default 10 seconds)
Returns
The latency in milliseconds
Exceptions
TimeoutExceptionif engine fails to respond within timeout period

◆ quit()

template<class Move >
void UCILoader::EngineInstance< Move >::quit
inline

Manually terminate the engine process.

Note: Manually calling this method is unnecessary. The engine will be automatically terminated when the EngineInstance object goes out of scope via the destructor.

However, manual termination is allowed for exceptional cases, such as when the engine becomes stuck in an infinite loop or is otherwise unresponsive. In such scenarios, calling quit() will forcibly shut down the engine process.

Warning
Important: After calling quit() manually, the EngineInstance object becomes unusable. Do not attempt to perform any operations other than health check (search, sync, option configuration, etc.) on the EngineInstance after calling this method.

◆ search()

template<class Move >
std::shared_ptr< SearchConnection< Move > > UCILoader::EngineInstance< Move >::search ( const GoParams< Move > &  params,
const PositionFormatter pos,
const std::vector< Move >  moves = {} 
)
inline

Start a new search operation with specified parameters.

Template Parameters
MoveThe move type
Parameters
paramsSearch parameters (time, depth, nodes, etc.) - see GoParamsBuilder from UCI.h
posRoot position to analyze - must implement PositionFormatter interface
movesSequence of moves to play before the search position (useful for openings)
Returns
Shared pointer to the SearchConnection for monitoring and controlling the search
Exceptions
EngineBusyExceptionif a search is already in progress

Example with StandardChess variant:

std::vector<StandardChessMove> moves = {e2e4, e7e5, g1f3};
auto search = engine->search(
GoParamsBuilder().depth(20).build(),
StartPos(),
moves
);
search->waitFor(std::chrono::seconds(5));
if (search->getStatus() == ResultReady) {
auto result = search->getResult();
// Process bestMove and optional ponderMove
}

The position parameter determines the root position, while moves specify which moves the engine must play before reaching the actual search position.

◆ sync()

template<class Move >
void UCILoader::EngineInstance< Move >::sync ( std::chrono::milliseconds  timeout = std::chrono::milliseconds(10000))
inline

Synchronize engine state with local representation.

Sends an 'isready' command to the engine and waits for the 'readyok' response. This ensures the engine is responsive and have all options and metadata (name, author) loaded.

This method should be called after constructing an EngineInstance and before performing operations like querying options or starting searches.

Parameters
timeoutMaximum time to wait for engine response (default 10 seconds)
Exceptions
TimeoutExceptionif engine fails to respond within timeout period

If a timeout occurs, the engine process will be terminated and this exception thrown. After a timeout, the EngineInstance should be considered unusable.

◆ ucinewgame()

template<class Move >
void UCILoader::EngineInstance< Move >::ucinewgame
inline

Send the ucinewgame command to the engine.

Instructs the engine to reset its internal state (typically clearing the transposition table) before starting future searches. Useful when starting a new game or test suite.

Member Data Documentation

◆ options

template<class Move >
EngineOptionsMap UCILoader::EngineInstance< Move >::options

Map of available engine options.

Populated automatically from UCI option responses. Use sync() to ensure all options are loaded.


The documentation for this class was generated from the following file: