00001 //---------------------------------------------------------------------------- 00002 /** @file SgGtpClient.cpp 00003 See SgGtpClient.h */ 00004 //---------------------------------------------------------------------------- 00005 00006 #include "SgSystem.h" 00007 #include "SgGtpClient.h" 00008 00009 #include <sstream> 00010 #include "SgDebug.h" 00011 00012 using namespace std; 00013 00014 //---------------------------------------------------------------------------- 00015 00016 SgGtpFailure::SgGtpFailure(const std::string& message) 00017 : SgException(message) 00018 { 00019 } 00020 00021 //---------------------------------------------------------------------------- 00022 00023 SgGtpClient::SgGtpClient(istream& in, ostream& out, bool verbose) 00024 : m_verbose(verbose), 00025 m_in(in), 00026 m_out(out) 00027 { 00028 } 00029 00030 SgGtpClient::~SgGtpClient() 00031 { 00032 } 00033 00034 string SgGtpClient::Send(const string& command) 00035 { 00036 m_out << command << '\n'; 00037 m_out.flush(); 00038 if (m_verbose) 00039 SgDebug() << "<< " << command << '\n'; 00040 if (! m_out) 00041 throw SgGtpFailure("GTP write connection is broken"); 00042 ostringstream response; 00043 bool done = false; 00044 bool isFirst = true; 00045 bool success = true; 00046 while (! done) 00047 { 00048 string line; 00049 getline(m_in, line); 00050 if (! m_in) 00051 throw SgGtpFailure("GTP read connection is broken"); 00052 if (m_verbose) 00053 SgDebug() << ">> " << line << '\n'; 00054 if (isFirst) 00055 { 00056 if (line.size() < 2 || (line[0] != '=' && line[0] != '?') 00057 || line[1] != ' ') 00058 throw SgGtpFailure("Invalid response: '" + line + "'"); 00059 if (line[0] == '?') 00060 success = false; 00061 line = line.substr(2); 00062 response << line; 00063 isFirst = false; 00064 } 00065 else 00066 { 00067 if (line.empty()) 00068 done = true; 00069 else 00070 response << '\n' << line; 00071 } 00072 } 00073 if (! success) 00074 throw SgGtpFailure(response.str()); 00075 return response.str(); 00076 } 00077 00078 //----------------------------------------------------------------------------