Esempio n. 1
0
"Not used"

import os
import time

from paramiko.client import SSHClient, AutoAddPolicy, socket

hosts_filename = os.path.expanduser("~/.ssh/paramiko_known_hosts")
#print hosts_filename

client = SSHClient()
if os.path.isfile(hosts_filename):
    client.load_host_keys(hosts_filename) #'~/.ssh/known_hosts'
client.set_missing_host_key_policy(AutoAddPolicy())
print client.get_host_keys()
client.connect('localhost', 2200, username='******', password='******')
client.save_host_keys(hosts_filename)
#print client.get_host_keys()
channel = client.invoke_shell()
channel.settimeout(0)
#time.sleep(1)
def datas(data=''):
    while True:
        try:
            res = channel.recv(10000)
            if len(res) == 0:
                exit(0)
            data += res
            cmds = data.split('\n')
            for r in cmds[:-1]:
Esempio n. 2
0
class USIEngine:
    def __init__(self,
                 name,
                 host,
                 engine_path,
                 nodes=None,
                 multiPV=1,
                 threads=1,
                 delay=0,
                 delay2=0):
        self.name = name
        self.nodes = nodes
        self.multiPV = multiPV
        self.quit_event = threading.Event()

        self.client = SSHClient()
        self.client.set_missing_host_key_policy(paramiko.client.WarningPolicy)
        #self.client.load_system_host_keys()
        keys = self.client.get_host_keys()
        keys.clear()
        self.client.connect(host)
        dirname = os.path.dirname(engine_path)
        command = f'cd {dirname} && {engine_path}'
        self.stdin, self.stdout, self.stderr = \
                self.client.exec_command(command, bufsize=0)

        self.queue = queue.Queue()
        self.watcher_thread = threading.Thread(target=self.stream_watcher,
                                               name='engine_watcher',
                                               args=(self.stdout, ))
        self.watcher_thread.start()
        self.pvs = [[]] * multiPV
        self.status = 'wait'
        self.position = 'startpos'

        self.send('usi')
        self.wait_for('usiok')
        self.set_option('Threads', threads)
        self.set_option('USI_Ponder', 'false')
        self.set_option('NetworkDelay', delay)
        self.set_option('NetworkDelay2', delay2)
        self.set_option('MultiPV', multiPV)
        if nodes:
            self.set_option('NodesLimit', nodes)
        #self.send('isready')
        #self.wait_for('readyok')

    def stream_watcher(self, stream):
        # for line in iter(stream.readline, b''):
        prog = re.compile('.*score cp (-?\d+) (?:multipv (\d+))? .*pv (.+)$')
        #for line in iter(stream.readline, b''):
        while (not self.quit_event.isSet()) and (not stream.closed):
            line = stream.readline().strip()
            if len(line):
                logging.debug(f'{self.name} > {line}')
                print(f'info string {self.name} > {line}', flush=True)
                match = prog.match(line)
                if match:
                    logging.debug(f'match: {match.group(1, 2, 3)}')
                    if match.group(2):
                        # multi PV
                        num = int(match.group(2)) - 1
                    else:
                        # single PV
                        num = 0
                    logging.debug(f'{self.name}: Found score of pv {num}')
                    self.pvs[num] = [int(match.group(1)), match.group(3)]

                # bestmove
                if line.startswith('bestmove'):
                    self.status = 'wait'

                self.queue.put(line)
        logging.debug(f'{self.name}: terminating the engine watcher thread')

    def set_option(self, name, value):
        self.send(f'setoption name {name} value {value}')

    def __del__(self):
        pass
        #self.terminate()

    def terminate(self):
        self.stop()
        self.quit_event.set()
        self.send('usi')
        self.watcher_thread.join(1)
        self.send('quit')
        self.status = 'quit'
        #self.client.close()

    def send(self, command):
        logging.debug(f'sending {command} to {self.name}')
        print(f'info string sending {command} to {self.name}', flush=True)
        self.stdin.write((command + '\n').encode('utf-8'))
        self.stdin.flush()

    def wait_for(self, command):
        logging.debug(f'{self.name}: waiting for {command}')
        lines = ""
        while self.client.get_transport().is_active():
            line = self.queue.get()
            lines += f'{line}\n'
            if (line == command):
                logging.debug(f'{self.name}: found {command}')
                self.status = 'wait'
                return lines

    def wait_for_bestmove(self):
        logging.debug(f'{self.name}: waiting for bestmove...')
        infostr(f'{self.name}: waiting for bestmove...')
        while self.client.get_transport().is_active():
            line = self.queue.get()
            if (line.startswith('bestmove')):
                logging.debug(f'{self.name}: found bestmove')
                infostr(f'{self.name}: found bestmove')
                bestmove = line[9:].split()[0].strip()
                self.status = 'wait'
                return bestmove

    def set_position(self, pos):
        self.position = pos
        self.send(f'position {pos}')

    def clear_queue(self):
        while True:
            try:
                line = self.queue.get_nowait()
                print(f'info string {self.name}: clearing queue: {line}',
                      flush=True)
            except queue.Empty:
                break

    def ponder(self, command):
        infostr(f'{self.name}: in ponder()')
        self.go_command = command
        if 'ponder' not in command:
            command = command.replace('go', 'go ponder')
        self.send(command)
        self.status = 'ponder'
        infostr(f'{self.name}: end of ponder()')

    def stop(self):
        infostr(f'{self.name}: in stop()')
        if self.status in ['go', 'ponder']:
            self.send('stop')
            self.wait_for_bestmove()
            self.status = 'wait'