2 * Copyright (c) 2018. Developed by Hedgecode.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org.hedgecode.chess.uci;
19 import java.io.IOException;
20 import java.util.List;
22 import org.hedgecode.chess.uci.annotation.CommandDirection;
23 import org.hedgecode.chess.uci.command.CommandParams;
26 * External UCI Engine Runner.
28 * @author Dmitry Samoshin aka gotty
30 public final class ExternalEngineRunner implements EngineRunner {
32 private Process process;
33 private ProcessBuilder processBuilder;
35 private ExternalEngine engine;
37 private boolean isInit = false;
39 ExternalEngineRunner(String extEngineCommand) {
40 processBuilder = new ProcessBuilder(extEngineCommand);
43 ExternalEngineRunner(List<String> extEngineCommands) {
44 processBuilder = new ProcessBuilder(extEngineCommands);
48 public Engine init() throws EngineException {
50 throw new EngineException("uci.engine.already.init");
53 process = processBuilder.start();
54 } catch (IOException e) {
55 throw new EngineException("uci.engine.external.start", e.getLocalizedMessage());
58 engine = new ExternalEngine(
59 process.getInputStream(),
60 process.getOutputStream()
68 public void run(final CommandExecutor commandExecutor) throws EngineException {
70 throw new EngineException("uci.engine.not.init");
72 Thread engineThread = new Thread(
75 Transmitter<String> engineTransmitter = engine.transmitter();
77 while (engineTransmitter.hasCommand()) {
78 String command = engineTransmitter.transmitCommand();
79 if (command.isEmpty()) continue;
80 CommandParams commandParams = new CommandParams(command);
82 commandParams.getName(),
83 CommandDirection.FROM_ENGINE,
84 commandParams.getParams()
89 UCIConstants.TERMINATE,
90 CommandDirection.FROM_ENGINE,
93 engineTransmitter.stop();
94 engineTransmitter.close();
95 if (process.isAlive()) process.destroy();
101 engineThread.start();