4 # remoteglot - Connects an abitrary UCI-speaking engine to ICS for easier post-game
5 # analysis, or for live analysis of relayed games. (Do not use for
6 # cheating! Cheating is bad for your karma, and your abuser flag.)
8 # Copyright 2007 Steinar H. Gunderson <sgunderson@bigfoot.com>
9 # Licensed under the GNU General Public License, version 2.
15 use Chess::PGN::Parse;
23 require 'Position.pm';
31 my $latest_update = undef;
32 my $output_timer = undef;
33 my $http_timer = undef;
34 my $tb_retry_timer = undef;
36 my $tb_lookup_running = 0;
40 open(FICSLOG, ">ficslog.txt")
41 or die "ficslog.txt: $!";
42 print FICSLOG "Log starting.\n";
46 open(UCILOG, ">ucilog.txt")
47 or die "ucilog.txt: $!";
48 print UCILOG "Log starting.\n";
52 open(TBLOG, ">tblog.txt")
53 or die "tblog.txt: $!";
54 print TBLOG "Log starting.\n";
60 # open the chess engine
61 my $engine = open_engine($remoteglotconf::engine_cmdline, 'E1', sub { handle_uci(@_, 1); });
62 my $engine2 = open_engine($remoteglotconf::engine2_cmdline, 'E2', sub { handle_uci(@_, 0); });
65 my ($pos_waiting, $pos_calculating, $pos_calculating_second_engine);
67 uciprint($engine, "setoption name UCI_AnalyseMode value true");
68 while (my ($key, $value) = each %remoteglotconf::engine_config) {
69 uciprint($engine, "setoption name $key value $value");
71 uciprint($engine, "ucinewgame");
73 if (defined($engine2)) {
74 uciprint($engine2, "setoption name UCI_AnalyseMode value true");
75 while (my ($key, $value) = each %remoteglotconf::engine2_config) {
76 uciprint($engine2, "setoption name $key value $value");
78 uciprint($engine2, "setoption name MultiPV value 500");
79 uciprint($engine2, "ucinewgame");
82 print "Chess engine ready.\n";
85 my $t = Net::Telnet->new(Timeout => 10, Prompt => '/fics% /');
86 $t->input_log(\*FICSLOG);
87 $t->open($remoteglotconf::server);
88 $t->print($remoteglotconf::nick);
89 $t->waitfor('/Press return to enter the server/');
93 $t->cmd("set shout 0");
94 $t->cmd("set seek 0");
95 $t->cmd("set style 12");
97 my $ev1 = AnyEvent->io(
100 cb => sub { # what callback to execute
102 my $line = $t->getline(Timeout => 0, errmode => 'return');
103 return if (!defined($line));
111 if (defined($remoteglotconf::target)) {
112 if ($remoteglotconf::target =~ /^http:/) {
113 fetch_pgn($remoteglotconf::target);
115 $t->cmd("observe $remoteglotconf::target");
118 print "FICS ready.\n";
120 # Engine events have already been set up by Engine.pm.
124 my ($engine, $line, $primary) = @_;
126 return if $line =~ /(upper|lower)bound/;
128 $line =~ s/ / /g; # Sometimes needed for Zappa Mexico
129 print UCILOG localtime() . " $engine->{'tag'} <= $line\n";
130 if ($line =~ /^info/) {
131 my (@infos) = split / /, $line;
134 parse_infos($engine, @infos);
136 if ($line =~ /^id/) {
137 my (@ids) = split / /, $line;
140 parse_ids($engine, @ids);
142 if ($line =~ /^bestmove/) {
144 return if (!$remoteglotconf::uci_assume_full_compliance);
145 if (defined($pos_waiting)) {
146 uciprint($engine, "position fen " . $pos_waiting->fen());
147 uciprint($engine, "go infinite");
149 $pos_calculating = $pos_waiting;
150 $pos_waiting = undef;
153 $engine2->{'info'} = {};
154 my $pos = $pos_waiting // $pos_calculating;
155 uciprint($engine2, "position fen " . $pos->fen());
156 uciprint($engine2, "go infinite");
157 $pos_calculating_second_engine = $pos;
163 my $getting_movelist = 0;
164 my $pos_for_movelist = undef;
165 my @uci_movelist = ();
166 my @pretty_movelist = ();
170 if ($line =~ /^<12> /) {
171 handle_position(Position->new($line));
174 if ($line =~ /^Movelist for game /) {
175 my $pos = $pos_waiting // $pos_calculating;
178 @pretty_movelist = ();
179 $pos_for_movelist = Position->start_pos($pos->{'player_w'}, $pos->{'player_b'});
180 $getting_movelist = 1;
183 if ($getting_movelist &&
184 $line =~ /^\s* \d+\. \s+ # move number
185 (\S+) \s+ \( [\d:.]+ \) \s* # first move, then time
186 (?: (\S+) \s+ \( [\d:.]+ \) )? # second move, then time
190 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($1);
191 push @uci_movelist, $uci_move;
192 push @pretty_movelist, $1;
195 ($pos_for_movelist, $uci_move) = $pos_for_movelist->make_pretty_move($2);
196 push @uci_movelist, $uci_move;
197 push @pretty_movelist, $2;
201 warn "Error when getting FICS move history: $@";
202 $getting_movelist = 0;
205 if ($getting_movelist &&
206 $line =~ /^\s+ \{.*\} \s+ (?: \* | 1\/2-1\/2 | 0-1 | 1-0 )/x) {
208 for my $pos ($pos_waiting, $pos_calculating) {
209 next if (!defined($pos));
210 if ($pos->fen() eq $pos_for_movelist->fen()) {
211 $pos->{'history'} = \@uci_movelist;
212 $pos->{'pretty_history'} = \@pretty_movelist;
215 $getting_movelist = 0;
217 if ($line =~ /^([A-Za-z]+)(?:\([A-Z]+\))* tells you: (.*)$/) {
218 my ($who, $msg) = ($1, $2);
220 next if (grep { $_ eq $who } (@remoteglotconf::masters) == 0);
222 if ($msg =~ /^fics (.*?)$/) {
223 $t->cmd("tell $who Executing '$1' on FICS.");
225 } elsif ($msg =~ /^uci (.*?)$/) {
226 $t->cmd("tell $who Sending '$1' to the engine.");
227 print { $engine->{'write'} } "$1\n";
228 } elsif ($msg =~ /^pgn (.*?)$/) {
230 $t->cmd("tell $who Starting to poll '$url'.");
232 } elsif ($msg =~ /^stoppgn$/) {
233 $t->cmd("tell $who Stopping poll.");
235 } elsif ($msg =~ /^quit$/) {
236 $t->cmd("tell $who Bye bye.");
239 $t->cmd("tell $who Couldn't understand '$msg', sorry.");
242 #print "FICS: [$line]\n";
245 # Starts periodic fetching of PGNs from the given URL.
248 AnyEvent::HTTP::http_get($url, sub {
249 handle_pgn(@_, $url);
253 my ($last_pgn_white, $last_pgn_black);
254 my @last_pgn_uci_moves = ();
255 my $pgn_hysteresis_counter = 0;
258 my ($body, $header, $url) = @_;
259 my $pgn = Chess::PGN::Parse->new(undef, $body);
260 if (!defined($pgn) || !$pgn->read_game()) {
261 warn "Error in parsing PGN from $url\n";
263 $pgn->quick_parse_game;
264 my $pos = Position->start_pos($pgn->white, $pgn->black);
265 my $moves = $pgn->moves;
267 for my $move (@$moves) {
269 ($pos, $uci_move) = $pos->make_pretty_move($move);
270 push @uci_moves, $uci_move;
272 $pos->{'history'} = \@uci_moves;
273 $pos->{'pretty_history'} = $moves;
275 # Sometimes, PGNs lose a move or two for a short while,
276 # or people push out new ones non-atomically.
277 # Thus, if we PGN doesn't change names but becomes
278 # shorter, we mistrust it for a few seconds.
280 if (defined($last_pgn_white) && defined($last_pgn_black) &&
281 $last_pgn_white eq $pgn->white &&
282 $last_pgn_black eq $pgn->black &&
283 scalar(@uci_moves) < scalar(@last_pgn_uci_moves)) {
284 if (++$pgn_hysteresis_counter < 3) {
289 $last_pgn_white = $pgn->white;
290 $last_pgn_black = $pgn->black;
291 @last_pgn_uci_moves = @uci_moves;
292 $pgn_hysteresis_counter = 0;
293 handle_position($pos);
297 $http_timer = AnyEvent->timer(after => 1.0, cb => sub {
302 sub handle_position {
305 # if this is already in the queue, ignore it
306 return if (defined($pos_waiting) && $pos->fen() eq $pos_waiting->fen());
308 # if we're already chewing on this and there's nothing else in the queue,
310 return if (!defined($pos_waiting) && defined($pos_calculating) &&
311 $pos->fen() eq $pos_calculating->fen());
313 # if we're already thinking on something, stop and wait for the engine
315 if (defined($pos_calculating)) {
316 if (!defined($pos_waiting)) {
317 uciprint($engine, "stop");
319 if ($remoteglotconf::uci_assume_full_compliance) {
322 uciprint($engine, "position fen " . $pos->fen());
323 uciprint($engine, "go infinite");
324 $pos_calculating = $pos;
327 # it's wrong just to give the FEN (the move history is useful,
328 # and per the UCI spec, we should really have sent "ucinewgame"),
330 uciprint($engine, "position fen " . $pos->fen());
331 uciprint($engine, "go infinite");
332 $pos_calculating = $pos;
335 if (defined($engine2)) {
336 if (defined($pos_calculating_second_engine)) {
337 uciprint($engine2, "stop");
339 uciprint($engine2, "position fen " . $pos->fen());
340 uciprint($engine2, "go infinite");
341 $pos_calculating_second_engine = $pos;
343 $engine2->{'info'} = {};
346 $engine->{'info'} = {};
349 schedule_tb_lookup();
352 # Output a command every move to note that we're
353 # still paying attention -- this is a good tradeoff,
354 # since if no move has happened in the last half
355 # hour, the analysis/relay has most likely stopped
356 # and we should stop hogging server resources.
362 my ($engine, @x) = @_;
365 my $info = $engine->{'info'};
367 # Search for "multipv" first of all, since e.g. Stockfish doesn't put it first.
368 for my $i (0..$#x - 1) {
369 if ($x[$i] eq 'multipv') {
375 while (scalar @x > 0) {
376 if ($x[0] eq 'multipv') {
382 if ($x[0] eq 'currmove' || $x[0] eq 'currmovenumber' || $x[0] eq 'cpuload') {
384 my $value = shift @x;
385 $info->{$key} = $value;
388 if ($x[0] eq 'depth' || $x[0] eq 'seldepth' || $x[0] eq 'hashfull' ||
389 $x[0] eq 'time' || $x[0] eq 'nodes' || $x[0] eq 'nps' ||
392 my $value = shift @x;
393 $info->{$key . $mpv} = $value;
396 if ($x[0] eq 'score') {
399 delete $info->{'score_cp' . $mpv};
400 delete $info->{'score_mate' . $mpv};
402 while ($x[0] eq 'cp' || $x[0] eq 'mate') {
405 $info->{'score_cp' . $mpv} = shift @x;
406 } elsif ($x[0] eq 'mate') {
408 $info->{'score_mate' . $mpv} = shift @x;
416 $info->{'pv' . $mpv} = [ @x[1..$#x] ];
419 if ($x[0] eq 'string' || $x[0] eq 'UCI_AnalyseMode' || $x[0] eq 'setting' || $x[0] eq 'contempt') {
423 #print "unknown info '$x[0]', trying to recover...\n";
425 die "Unknown info '" . join(',', @x) . "'";
431 my ($engine, @x) = @_;
433 while (scalar @x > 0) {
434 if ($x[0] =~ /^(name|author)$/) {
436 my $value = join(' ', @x);
437 $engine->{'id'}{$key} = $value;
446 sub prettyprint_pv_no_cache {
447 my ($board, @pvs) = @_;
449 if (scalar @pvs == 0 || !defined($pvs[0])) {
454 my ($from_col, $from_row, $to_col, $to_row, $promo) = parse_uci_move($pv);
455 my ($pretty, $nb) = $board->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
456 return ( $pretty, prettyprint_pv_no_cache($nb, @pvs) );
460 my ($pos, @pvs) = @_;
462 my $cachekey = join('', @pvs);
463 if (exists($pos->{'prettyprint_cache'}{$cachekey})) {
464 return @{$pos->{'prettyprint_cache'}{$cachekey}};
466 my @res = prettyprint_pv_no_cache($pos->{'board'}, @pvs);
467 $pos->{'prettyprint_cache'}{$cachekey} = \@res;
475 return if (!defined($pos_calculating));
477 # Don't update too often.
478 my $age = Time::HiRes::tv_interval($latest_update);
479 if ($age < $remoteglotconf::update_max_interval) {
480 my $wait = $remoteglotconf::update_max_interval + 0.01 - $age;
481 $output_timer = AnyEvent->timer(after => $wait, cb => \&output);
485 my $info = $engine->{'info'};
488 # If we have tablebase data from a previous lookup, replace the
489 # engine data with the data from the tablebase.
491 my $fen = $pos_calculating->fen();
492 if (exists($tb_cache{$fen})) {
493 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
494 delete $info->{$key . '1'};
495 delete $info->{$key};
497 $info->{'nodes'} = 0;
499 $info->{'depth'} = 0;
500 $info->{'seldepth'} = 0;
501 $info->{'tbhits'} = 0;
503 my $t = $tb_cache{$fen};
505 my $matelen = int((1 + scalar @$pv) / 2);
506 if ($t->{'result'} eq '1/2-1/2') {
507 $info->{'score_cp'} = 0;
508 } elsif ($t->{'result'} eq '1-0') {
509 if ($pos_calculating->{'toplay'} eq 'B') {
510 $info->{'score_mate'} = -$matelen;
512 $info->{'score_mate'} = $matelen;
515 if ($pos_calculating->{'toplay'} eq 'B') {
516 $info->{'score_mate'} = $matelen;
518 $info->{'score_mate'} = -$matelen;
522 $info->{'tablebase'} = 1;
524 $info->{'tablebase'} = 0;
528 # Some programs _always_ report MultiPV, even with only one PV.
529 # In this case, we simply use that data as if MultiPV was never
532 if (exists($info->{'pv1'}) && !exists($info->{'pv2'})) {
533 for my $key (qw(pv score_cp score_mate nodes nps depth seldepth tbhits)) {
534 if (exists($info->{$key . '1'})) {
535 $info->{$key} = $info->{$key . '1'};
541 # Check the PVs first. if they're invalid, just wait, as our data
542 # is most likely out of sync. This isn't a very good solution, as
543 # it can frequently miss stuff, but it's good enough for most users.
547 if (exists($info->{'pv'})) {
548 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv'}});
552 while (exists($info->{'pv' . $mpv})) {
553 $dummy = prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}});
558 $engine->{'info'} = {};
564 $latest_update = [Time::HiRes::gettimeofday];
568 my $info = $engine->{'info'};
569 my $id = $engine->{'id'};
571 my $text = 'Analysis';
572 if ($pos_calculating->{'last_move'} ne 'none') {
573 if ($pos_calculating->{'toplay'} eq 'W') {
574 $text .= sprintf ' after %u. ... %s', ($pos_calculating->{'move_num'}-1), $pos_calculating->{'last_move'};
576 $text .= sprintf ' after %u. %s', $pos_calculating->{'move_num'}, $pos_calculating->{'last_move'};
578 if (exists($id->{'name'})) {
583 if (exists($id->{'name'})) {
584 $text .= " by $id->{'name'}:\n\n";
589 return unless (exists($pos_calculating->{'board'}));
591 if (exists($info->{'pv1'}) && exists($info->{'pv2'})) {
594 while (exists($info->{'pv' . $mpv})) {
595 $text .= sprintf " PV%2u", $mpv;
596 my $score = short_score($info, $pos_calculating, $mpv);
597 $text .= " ($score)" if (defined($score));
600 if (exists($info->{'tbhits' . $mpv}) && $info->{'tbhits' . $mpv} > 0) {
601 if ($info->{'tbhits' . $mpv} == 1) {
602 $tbhits = ", 1 tbhit";
604 $tbhits = sprintf ", %u tbhits", $info->{'tbhits' . $mpv};
608 if (exists($info->{'nodes' . $mpv}) && exists($info->{'nps' . $mpv}) && exists($info->{'depth' . $mpv})) {
609 $text .= sprintf " (%5u kn, %3u kn/s, %2u ply$tbhits)",
610 $info->{'nodes' . $mpv} / 1000, $info->{'nps' . $mpv} / 1000, $info->{'depth' . $mpv};
614 $text .= " " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv' . $mpv}})) . "\n";
620 my $score = long_score($info, $pos_calculating, '');
621 $text .= " $score\n" if defined($score);
622 $text .= " PV: " . join(', ', prettyprint_pv($pos_calculating, @{$info->{'pv'}}));
625 if (exists($info->{'nodes'}) && exists($info->{'nps'}) && exists($info->{'depth'})) {
626 $text .= sprintf " %u nodes, %7u nodes/sec, depth %u ply",
627 $info->{'nodes'}, $info->{'nps'}, $info->{'depth'};
629 if (exists($info->{'seldepth'})) {
630 $text .= sprintf " (%u selective)", $info->{'seldepth'};
632 if (exists($info->{'tbhits'}) && $info->{'tbhits'} > 0) {
633 if ($info->{'tbhits'} == 1) {
634 $text .= ", one Syzygy hit";
636 $text .= sprintf ", %u Syzygy hits", $info->{'tbhits'};
642 #$text .= book_info($pos_calculating->fen(), $pos_calculating->{'board'}, $pos_calculating->{'toplay'});
644 my @refutation_lines = ();
645 if (defined($engine2)) {
646 for (my $mpv = 1; $mpv < 500; ++$mpv) {
647 my $info = $engine2->{'info'};
648 last if (!exists($info->{'pv' . $mpv}));
650 my $pv = $info->{'pv' . $mpv};
652 my $pretty_move = join('', prettyprint_pv($pos_calculating_second_engine, $pv->[0]));
653 my @pretty_pv = prettyprint_pv($pos_calculating_second_engine, @$pv);
654 if (scalar @pretty_pv > 5) {
655 @pretty_pv = @pretty_pv[0..4];
656 push @pretty_pv, "...";
658 my $key = $pretty_move;
659 my $line = sprintf(" %-6s %6s %3s %s",
661 short_score($info, $pos_calculating_second_engine, $mpv),
662 "d" . $info->{'depth' . $mpv},
663 join(', ', @pretty_pv));
664 push @refutation_lines, [ $key, $line ];
669 if ($#refutation_lines >= 0) {
670 $text .= "Shallow search of all legal moves:\n\n";
671 for my $line (sort { $a->[0] cmp $b->[0] } @refutation_lines) {
672 $text .= $line->[1] . "\n";
677 if ($last_text ne $text) {
678 print "
\e[H
\e[2J"; # clear the screen
685 my $info = $engine->{'info'};
688 $json->{'position'} = $pos_calculating->to_json_hash();
689 $json->{'id'} = $engine->{'id'};
690 $json->{'score'} = long_score($info, $pos_calculating, '');
691 $json->{'short_score'} = short_score($info, $pos_calculating, '');
693 $json->{'nodes'} = $info->{'nodes'};
694 $json->{'nps'} = $info->{'nps'};
695 $json->{'depth'} = $info->{'depth'};
696 $json->{'tbhits'} = $info->{'tbhits'};
697 $json->{'seldepth'} = $info->{'seldepth'};
698 $json->{'tablebase'} = $info->{'tablebase'};
700 # single-PV only for now
701 $json->{'pv_uci'} = $info->{'pv'};
702 $json->{'pv_pretty'} = [ prettyprint_pv($pos_calculating, @{$info->{'pv'}}) ];
704 my %refutation_lines = ();
705 my @refutation_lines = ();
706 if (defined($engine2)) {
707 for (my $mpv = 1; $mpv < 500; ++$mpv) {
708 my $info = $engine2->{'info'};
709 my $pretty_move = "";
711 last if (!exists($info->{'pv' . $mpv}));
714 my $pv = $info->{'pv' . $mpv};
715 my $pretty_move = join('', prettyprint_pv($pos_calculating, $pv->[0]));
716 my @pretty_pv = prettyprint_pv($pos_calculating, @$pv);
717 $refutation_lines{$pv->[0]} = {
718 sort_key => $pretty_move,
719 depth => $info->{'depth' . $mpv},
720 score_sort_key => score_sort_key($info, $pos_calculating, $mpv, 0),
721 pretty_score => short_score($info, $pos_calculating, $mpv),
722 pretty_move => $pretty_move,
723 pv_pretty => \@pretty_pv,
725 $refutation_lines{$pv->[0]}->{'pv_uci'} = $pv;
729 $json->{'refutation_lines'} = \%refutation_lines;
731 open my $fh, ">", $remoteglotconf::json_output . ".tmp"
733 print $fh JSON::XS::encode_json($json);
735 rename($remoteglotconf::json_output . ".tmp", $remoteglotconf::json_output);
739 my ($engine, $msg) = @_;
740 $engine->print($msg);
741 print UCILOG localtime() . " $engine->{'tag'} => $msg\n";
745 my ($info, $pos, $mpv) = @_;
747 my $invert = ($pos->{'toplay'} eq 'B');
748 if (defined($info->{'score_mate' . $mpv})) {
750 return sprintf "M%3d", -$info->{'score_mate' . $mpv};
752 return sprintf "M%3d", $info->{'score_mate' . $mpv};
755 if (exists($info->{'score_cp' . $mpv})) {
756 my $score = $info->{'score_cp' . $mpv} * 0.01;
758 if ($info->{'tablebase'}) {
767 return sprintf "%+5.2f", $score;
775 my ($info, $pos, $mpv, $invert) = @_;
777 if (defined($info->{'score_mate' . $mpv})) {
778 my $mate = $info->{'score_mate' . $mpv};
782 $score = 99999 - $mate;
784 # Side to move is getting mated (note the double negative for $mate)
785 $score = -99999 - $mate;
792 if (exists($info->{'score_cp' . $mpv})) {
793 my $score = $info->{'score_cp' . $mpv};
805 my ($info, $pos, $mpv) = @_;
807 if (defined($info->{'score_mate' . $mpv})) {
808 my $mate = $info->{'score_mate' . $mpv};
809 if ($pos->{'toplay'} eq 'B') {
813 return sprintf "White mates in %u", $mate;
815 return sprintf "Black mates in %u", -$mate;
818 if (exists($info->{'score_cp' . $mpv})) {
819 my $score = $info->{'score_cp' . $mpv} * 0.01;
821 if ($info->{'tablebase'}) {
822 return "Theoretical draw";
824 return "Score: 0.00";
827 if ($pos->{'toplay'} eq 'B') {
830 return sprintf "Score: %+5.2f", $score;
839 my ($fen, $board, $toplay) = @_;
841 if (exists($book_cache{$fen})) {
842 return $book_cache{$fen};
845 my $ret = `./booklook $fen`;
846 return "" if ($ret =~ /Not found/ || $ret eq '');
850 for my $m (split /\n/, $ret) {
851 my ($move, $annotation, $win, $draw, $lose, $rating, $rating_div) = split /,/, $m;
855 $pmove = '(current)';
857 ($pmove) = prettyprint_pv_no_cache($board, $move);
858 $pmove .= $annotation;
862 if ($toplay eq 'W') {
863 $score = 1.0 * $win + 0.5 * $draw + 0.0 * $lose;
865 $score = 0.0 * $win + 0.5 * $draw + 1.0 * $lose;
867 my $n = $win + $draw + $lose;
873 $percent = sprintf "%4u%%", int(100.0 * $score / $n + 0.5);
876 push @moves, [ $pmove, $n, $percent, $rating ];
879 @moves[1..$#moves] = sort { $b->[2] cmp $a->[2] } @moves[1..$#moves];
881 my $text = "Book moves:\n\n Perf. N Rating\n\n";
883 $text .= sprintf " %-10s %s %6u %4s\n", $m->[0], $m->[2], $m->[1], $m->[3]
889 sub schedule_tb_lookup {
890 return if (!defined($remoteglotconf::tb_serial_key));
891 my $pos = $pos_waiting // $pos_calculating;
892 return if (exists($tb_cache{$pos->fen()}));
894 # If there's more than seven pieces, there's not going to be an answer,
896 return if ($pos->num_pieces() > 7);
898 # Max one at a time. If it's still relevant when it returns,
899 # schedule_tb_lookup() will be called again.
900 return if ($tb_lookup_running);
902 $tb_lookup_running = 1;
903 my $url = 'http://158.250.18.203:6904/tasks/addtask?auth.login=' .
904 $remoteglotconf::tb_serial_key .
905 '&auth.password=aquarium&type=0&fen=' .
906 URI::Escape::uri_escape($pos->fen());
907 print TBLOG "Downloading $url...\n";
908 AnyEvent::HTTP::http_get($url, sub {
909 handle_tb_lookup_return(@_, $pos, $pos->fen());
913 sub handle_tb_lookup_return {
914 my ($body, $header, $pos, $fen) = @_;
915 print TBLOG "Response for [$fen]:\n";
916 print TBLOG $header . "\n\n";
917 print TBLOG $body . "\n\n";
919 my $response = JSON::XS::decode_json($body);
920 if ($response->{'ErrorCode'} != 0) {
921 die "Unknown tablebase server error: " . $response->{'ErrorDesc'};
923 my $state = $response->{'Response'}{'StateString'};
924 if ($state eq 'COMPLETE') {
925 my $pgn = Chess::PGN::Parse->new(undef, $response->{'Response'}{'Moves'});
926 if (!defined($pgn) || !$pgn->read_game()) {
927 warn "Error in parsing PGN\n";
929 $pgn->quick_parse_game;
931 my $moves = $pgn->moves;
933 for my $move (@$moves) {
935 ($pvpos, $uci_move) = $pvpos->make_pretty_move($move);
936 push @uci_moves, $uci_move;
939 result => $pgn->result,
944 } elsif ($state =~ /QUEUED/ || $state =~ /PROCESSING/) {
945 # Try again in a second. Note that if we have changed
946 # position in the meantime, we might query a completely
947 # different position! But that's fine.
949 die "Unknown response state " . $state;
952 # Wait a second before we schedule another one.
953 $tb_retry_timer = AnyEvent->timer(after => 1.0, cb => sub {
954 $tb_lookup_running = 0;
955 schedule_tb_lookup();
959 warn "Error in tablebase lookup: $@";
961 # Don't try this one again, but don't block new lookups either.
962 $tb_lookup_running = 0;
967 my ($cmdline, $tag, $cb) = @_;
968 return undef if (!defined($cmdline));
969 return Engine->open($cmdline, $tag, $cb);
972 sub col_letter_to_num {
973 return ord(shift) - ord('a');
976 sub row_letter_to_num {
977 return 7 - (ord(shift) - ord('1'));
982 my $from_col = col_letter_to_num(substr($move, 0, 1));
983 my $from_row = row_letter_to_num(substr($move, 1, 1));
984 my $to_col = col_letter_to_num(substr($move, 2, 1));
985 my $to_row = row_letter_to_num(substr($move, 3, 1));
986 my $promo = substr($move, 4, 1);
987 return ($from_col, $from_row, $to_col, $to_row, $promo);