Ejemplo n.º 1
0
void TargetAltitude::sessionExecute (XmlRpcValue& params, XmlRpcValue& result)
{
	if (params.size () != 4)
		throw XmlRpcException ("Invalid number of parameters");
	if (((int) params[0]) < 0)
		throw XmlRpcException ("Target id < 0");
	rts2db::Target *tar = createTarget ((int) params[0], Configuration::instance ()->getObserver (), Configuration::instance ()->getObservatoryAltitude ());
	if (tar == NULL)
	{
		throw XmlRpcException ("Cannot create target");
	}
	time_t tfrom = (int)params[1];
	double jd_from = ln_get_julian_from_timet (&tfrom);
	time_t tto = (int)params[2];
	double jd_to = ln_get_julian_from_timet (&tto);
	double stepsize = ((double)params[3]) / 86400;
	// test for insane request
	if ((jd_to - jd_from) / stepsize > 10000)
	{
		throw XmlRpcException ("Too many points");
	}
	int i;
	double j;
	for (i = 0, j = jd_from; j < jd_to; i++, j += stepsize)
	{
		result[i][0] = j;
		ln_hrz_posn hrz;
		tar->getAltAz (&hrz, j);
		result[i][1] = hrz.alt;
	}
}
Ejemplo n.º 2
0
// Encode the request to call the specified method with the specified parameters into xml
bool XmlRpcClient::generateRequest(const char* methodName, XmlRpcValue const& params)
{
	std::string body = REQUEST_BEGIN;
	body += methodName;
	body += REQUEST_END_METHODNAME;
	// If params is an array, each element is a separate parameter
	if (params.valid())
	{
		body += PARAMS_TAG;
		if (params.getType() == XmlRpcValue::TypeArray)
		{
			for (int i=0; i<params.size(); ++i)
			{
				body += PARAM_TAG;
				body += params[i].toXml();
				body += PARAM_ETAG;
			}
		}
		else
		{
			body += PARAM_TAG;
			body += params.toXml();
			body += PARAM_ETAG;
		}
		body += PARAMS_ETAG;
	}
	body += REQUEST_END;
	std::string header = generateHeader(body);
	XmlRpcUtil::log(4, "XmlRpcClient::generateRequest: header is %d bytes, content-length is %d.",
					header.length(), body.length());
	_request = header + body;
	return true;
}
Ejemplo n.º 3
0
void RecordsAverage::sessionExecute (XmlRpcValue& params, XmlRpcValue& result)
{
	if (params.size () != 3)
		throw XmlRpcException ("Invalid number of parameters");

	try
	{
		rts2db::RecordAvgSet recset = rts2db::RecordAvgSet (params[0], rts2db::HOUR);
		int i = 0;
		time_t t;
		recset.load (params[1], params[2]);
		for (rts2db::RecordAvgSet::iterator iter = recset.begin (); iter != recset.end (); iter++)
		{
			rts2db::RecordAvg rv = (*iter);
			XmlRpcValue res;
			t = rv.getRecTime ();
			res[0] = XmlRpcValue (gmtime (&t));
			res[1] = rv.getAverage ();
			res[2] = rv.getMinimum ();
			res[3] = rv.getMaximum ();
			res[4] = rv.getRecCout ();
			result[i++] = res;
		}
	}
	catch (rts2db::SqlError err)
	{
		throw XmlRpcException (err.what ());
	}
}
Ejemplo n.º 4
0
void MasterStateIs::sessionExecute (XmlRpcValue& params, XmlRpcValue& result)
{
	int ms = ((HttpD *) getMasterApp ())->getMasterStateFull ();
	if (params.size () == 1)
	{
		if (params[0] == "on")
		{
			result = !(ms & SERVERD_ONOFF_MASK);
		}
		else if (params[0] == "standby")
		{
			result = (ms & SERVERD_ONOFF_MASK) == SERVERD_STANDBY;
		}
		else if (params[0] == "off")
		{
			result = (ms & SERVERD_ONOFF_MASK) == SERVERD_HARD_OFF
				|| (ms & SERVERD_ONOFF_MASK) == SERVERD_SOFT_OFF;
		}
		else if (params[0] == "rnight")
		{
			result = (ms & SERVERD_STATUS_MASK) == SERVERD_NIGHT && !(ms & SERVERD_ONOFF_MASK);
		}
		else
		{
			throw XmlRpcException ("Invalid status name parameter");
		}
	}
	else
	{
		throw XmlRpcException ("Invalid number of parameters");
	}
}
Ejemplo n.º 5
0
// Encode the request to call the specified method with the specified parameters into xml
bool
XmlRpcCurlClient::generateRequest(const char* methodName, XmlRpcValue const& params)
{
  std::string body = REQUEST_BEGIN;
  body += methodName;
  body += REQUEST_END_METHODNAME;

  // If params is an array, each element is a separate parameter
  if (params.valid()) {
    body += PARAMS_TAG;
    if (params.getType() == XmlRpcValue::TypeArray)
    {
      for (int i=0; i<params.size(); ++i) {
        body += PARAM_TAG;
        body += params[i].toXml();
        body += PARAM_ETAG;
      }
    }
    else
    {
      body += PARAM_TAG;
      body += params.toXml();
      body += PARAM_ETAG;
    }

    body += PARAMS_ETAG;
  }
  body += REQUEST_END;

  _request = body;
  return true;
}
Ejemplo n.º 6
0
	void execute(XmlRpcValue& params, XmlRpcValue& result)
	{
		int nArgs = params.size();
		int requiredSize;
		wchar_t wFieldText[129];
		bool ShowMsg=false;

		Log(2,L"RX: %d",nArgs);

		for (int i=0; i<nArgs; i++)
		{
			int y = (int) (params[i]["Row"]);
			int x = (int) (params[i]["Column"]);
			std::string& fieldText = params[i]["Field"];
			int attribute = params[i]["Attribute"];

			requiredSize = mbstowcs(NULL, fieldText.c_str(), 0); // C4996
			if (requiredSize>127) 
				requiredSize=127;

			mbstowcs(wFieldText,fieldText.c_str(),requiredSize+1);

			//row updated?
			if (0 != wcsncmp(ScreenContent[y]+x, wFieldText, wcslen(wFieldText)))
			{
				wcsncpy(ScreenContent[y]+x, wFieldText, wcslen(wFieldText));
				Log(2,L"R:%d C:%d <%s>",y,x,wFieldText);
			}
		}
		DumpScreenContent();

		result = "OK";
	}
Ejemplo n.º 7
0
void UserLogin::execute (struct sockaddr_in *saddr, XmlRpcValue& params, XmlRpcValue& result)
{
	if (params.size() != 2)
		throw XmlRpcException ("Invalid number of parameters");

	result = verifyUser (params[0], params[1]);
}
Ejemplo n.º 8
0
bool XMLRPCManager::validateXmlrpcResponse(const std::string& method, XmlRpcValue &response,
                                    XmlRpcValue &payload)
{
  if (response.getType() != XmlRpcValue::TypeArray)
  {
    ROSCPP_LOG_DEBUG("XML-RPC call [%s] didn't return an array",
        method.c_str());
    return false;
  }
  if (response.size() != 2 && response.size() != 3)
  {
    ROSCPP_LOG_DEBUG("XML-RPC call [%s] didn't return a 2 or 3-element array",
        method.c_str());
    return false;
  }
  if (response[0].getType() != XmlRpcValue::TypeInt)
  {
    ROSCPP_LOG_DEBUG("XML-RPC call [%s] didn't return a int as the 1st element",
        method.c_str());
    return false;
  }
  int status_code = response[0];
  if (response[1].getType() != XmlRpcValue::TypeString)
  {
    ROSCPP_LOG_DEBUG("XML-RPC call [%s] didn't return a string as the 2nd element",
        method.c_str());
    return false;
  }
  std::string status_string = response[1];
  if (status_code != 1)
  {
    ROSCPP_LOG_DEBUG("XML-RPC call [%s] returned an error (%d): [%s]",
        method.c_str(), status_code, status_string.c_str());
    return false;
  }
  if (response.size() > 2)
  {
    payload = response[2];
  }
  else
  {
    std::string empty_array = "<value><array><data></data></array></value>";
    int offset = 0;
    payload = XmlRpcValue(empty_array, &offset);
  }
  return true;
}
Ejemplo n.º 9
0
 void execute(XmlRpcValue& params, XmlRpcValue& result)
 {
     int nArgs = params.size();
     double sum = 0.0;
     for (int i=0; i<nArgs; ++i)
         sum += double(params[i]);
     result = sum;
 }
Ejemplo n.º 10
0
void ListTargetsByType::sessionExecute (XmlRpcValue& params, XmlRpcValue& result)
{
	char target_types[params.size ()+1];
	int j;
	for (j = 0; j < params.size (); j++)
		target_types[j] = *(((std::string)params[j]).c_str());
	target_types[j] = '\0';

	rts2db::TargetSet *tar_set = new rts2db::TargetSet (target_types);
	tar_set->load ();

	double value;
	int i = 0;
	XmlRpcValue retVar;

	double JD = ln_get_julian_from_sys ();

	for (rts2db::TargetSet::iterator tar_iter = tar_set->begin(); tar_iter != tar_set->end (); tar_iter++, i++)
	{
		rts2db::Target *tar = (*tar_iter).second;
		retVar["id"] = tar->getTargetID ();
		retVar["type"] = tar->getTargetType ();
		if (tar->getTargetName ())
			retVar["name"] = tar->getTargetName ();
		else
			retVar["name"] = "NULL";

		retVar["enabled"] = tar->getTargetEnabled ();
		if (tar->getTargetComment ())
			retVar["comment"] = tar->getTargetComment ();
		else
			retVar["comment"] = "";
		value = tar->getLastObs();
		retVar["last_obs"] = value;
		struct ln_equ_posn pos;
		tar->getPosition (&pos, JD);
		retVar["ra"] = pos.ra;
		retVar["dec"] = pos.dec;
		struct ln_hrz_posn hrz;
		tar->getAltAz (&hrz, JD);
		retVar["alt"] = hrz.alt;
		retVar["az"] = hrz.az;
		result[i++] = retVar;
	}
}
Ejemplo n.º 11
0
 void execute(XmlRpcValue& params, XmlRpcValue& result) 
 { 
      string tmp = params[0];
     vector<string> list = chat.Listar();
     for(int i = 0; i < list.size(); i++)
            result[i] = (string)list[i];
      
     cout << "Listando: " << result.size() <<  endl;
 } 
Ejemplo n.º 12
0
void DeviceType::sessionExecute (XmlRpcValue& params, XmlRpcValue &result)
{
	if (params.size () != 1)
		throw XmlRpcException ("Single device name expected");
	HttpD *serv = (HttpD *) getMasterApp ();
	rts2core::Connection *conn = serv->getOpenConnection (((std::string)params[0]).c_str());
	if (conn == NULL)
		throw XmlRpcException ("Cannot get device with name " + (std::string)params[0]);
	result = conn->getOtherType ();
}
Ejemplo n.º 13
0
void DeviceCommand::sessionExecute (XmlRpcValue& params, XmlRpcValue &result)
{
	if (params.size () != 2)
		throw XmlRpcException ("Device name and command (as single parameter) expected");
	HttpD *serv = (HttpD *) getMasterApp ();
	rts2core::Connection *conn = serv->getOpenConnection (((std::string)params[0]).c_str());
	if (conn == NULL)
		throw XmlRpcException ("Device named " + (std::string)params[0] + " does not exists");
	conn->queCommand (new rts2core::Command (serv, ((std::string)params[1]).c_str()));
}
Ejemplo n.º 14
0
static void AdvancedTest()
{
	XmlRpcValue args, result;

	// Passing datums:
	args[0] = "a string";
	args[1] = 1;
	args[2] = true;
	args[3] = 3.14159;
	struct tm timeNow;
	args[4] = XmlRpcValue(&timeNow);

	// Passing an array:
	XmlRpcValue array;
	array[0] = 4;
	array[1] = 5;
	array[2] = 6;
	args[5] = array;
	// Note: if there's a chance that the array contains zero elements,
	// you'll need to call:
	//      array.initAsArray();
	// ...because otherwise the type will never get set to "TypeArray" and
	// the value will be a "TypeInvalid".

	// Passing a struct:
	XmlRpcValue record;
	record["SOURCE"] = "a";
	record["DESTINATION"] = "b";
	record["LENGTH"] = 5;
	args[6] = record;
	// We don't support zero-size struct's...Surely no-one needs these?

	// Make the call:
	XmlRpcClient Connection("https://61.95.191.232:9600/arumate/rpc/xmlRpcServer.php");
	Connection.setIgnoreCertificateAuthority();
	if (! Connection.execute("arumate.getMegawatts", args, result)) {
		std::cout << Connection.getError();
		return;
	}

	// Pull the data out:
	if (result.getType() != XmlRpcValue::TypeStruct) {
		std::cout << "I was expecting a struct.";
		return;
	}
	int i = result["n"];
	std::string s = result["name"];
	array = result["A"];
	for (int i=0; i < array.size(); i++)
		std::cout << (int)array[i] << "\n";
	record = result["subStruct"];
	std::cout << (std::string)record["foo"] << "\n";
}
Ejemplo n.º 15
0
void XMLRPC2DIServer::xmlrpcval2amarg(XmlRpcValue& v, AmArg& a, 
				      unsigned int start_index) {
  if (v.valid()) {
    for (int i=start_index; i<v.size();i++) {
      switch (v[i].getType()) {
      case XmlRpcValue::TypeInt:   { a.push(AmArg((int)v[i]));    }  break;
      case XmlRpcValue::TypeDouble:{ a.push(AmArg((double)v[i])); }  break;
      case XmlRpcValue::TypeString:{ a.push(AmArg(((string)v[i]).c_str())); }  break;
	// TODO: support more types (datetime, struct, ...)
      default:     throw XmlRpcException("unsupported parameter type", 400);
      };
    }
  } 
}
Ejemplo n.º 16
0
void Login::execute (struct sockaddr_in *saddr, XmlRpcValue& params, XmlRpcValue& result)
{
	if (params.size () != 2)
	{
		throw XmlRpcException ("Invalid number of parameters");
	}

	if (verifyUser (params[0], params[1]) == false)
	{
		throw XmlRpcException ("Invalid login or password");
	}

	result = ((HttpD *) getMasterApp ())->addSession (params[0], 3600);
}
Ejemplo n.º 17
0
void XMLRPC2DIServerDIMethod::execute(XmlRpcValue& params, XmlRpcValue& result) {
  try {
    if (params.size() < 2) {
      DBG("XMLRPC2DI: ERROR: need at least factory name"
	  " and function name to call\n");
      throw XmlRpcException("need at least factory name"
			    " and function name to call", 400);
    }
    
    string fact_name = params[0];
    string fct_name = params[1];

    DBG("XMLRPC2DI: factory '%s' function '%s'\n", 
	fact_name.c_str(), fct_name.c_str());

    // get args
    AmArg args;
    XMLRPC2DIServer::xmlrpcval2amarg(params, args, 2);
  
    AmDynInvokeFactory* di_f = AmPlugIn::instance()->getFactory4Di(fact_name);
    if(!di_f){
      throw XmlRpcException("could not get factory", 500);
    }
    AmDynInvoke* di = di_f->getInstance();
    if(!di){
      throw XmlRpcException("could not get instance from factory", 500);
    }
    AmArg ret;
    di->invoke(fct_name, args, ret);
  
    XMLRPC2DIServer::amarg2xmlrpcval(ret, result);


  } catch (const XmlRpcException& e) {
    throw;
  } catch (const AmDynInvoke::NotImplemented& e) {
    throw XmlRpcException("Exception: AmDynInvoke::NotImplemented: "
			  + e.what, 504);
  } catch (const AmArg::OutOfBoundsException& e) {
    throw XmlRpcException("Exception: AmArg out of bounds - paramter number mismatch.", 300);
  } catch (const AmArg::TypeMismatchException& e) {
    throw XmlRpcException("Exception: Type mismatch in arguments.", 300);
  } catch (const string& e) {
    throw XmlRpcException("Exception: "+e, 500);
  } catch (...) {
    throw XmlRpcException("Exception occured.", 500);
  }
}
Ejemplo n.º 18
0
// Execute multiple calls and return the results in an array.
bool XmlRpcServerConnection::executeMulticall(const std::string& in_methodName, XmlRpcValue& params, XmlRpcValue& result)
{
	if (in_methodName != SYSTEM_MULTICALL) return false;

	// There ought to be 1 parameter, an array of structs
	if (params.size() != 1 || params[0].getType() != XmlRpcValue::TypeArray)
		throw XmlRpcException(SYSTEM_MULTICALL + ": Invalid argument (expected an array)");

	int nc = params[0].size();
	result.setSize(nc);

	for (int i=0; i<nc; ++i)
	{
		if ( ! params[0][i].hasMember(METHODNAME) ||
			! params[0][i].hasMember(PARAMS))
		{
			result[i][FAULTCODE] = -1;
			result[i][FAULTSTRING] = SYSTEM_MULTICALL +
				": Invalid argument (expected a struct with members methodName and params)";
			continue;
		}

		const std::string& methodName = params[0][i][METHODNAME];
		XmlRpcValue& methodParams = params[0][i][PARAMS];

		XmlRpcValue resultValue;
		resultValue.setSize(1);
		try
		{
			if ( ! executeMethod(methodName, methodParams, resultValue[0]) &&
				! executeMulticall(methodName, params, resultValue[0]))
			{
				result[i][FAULTCODE] = -1;
				result[i][FAULTSTRING] = methodName + ": unknown method name";
			}
			else
				result[i] = resultValue;

		}
		catch (const XmlRpcException& fault)
		{
			result[i][FAULTCODE] = fault.getCode();
			result[i][FAULTSTRING] = fault.getMessage();
		}
	}

	return true;
}
Ejemplo n.º 19
0
void TargetInfo::sessionExecute (XmlRpcValue& params, XmlRpcValue& result)
{
	std::list < int >targets;
	XmlRpcValue retVar;
	int i;
	double JD;

	for (i = 0; i < params.size(); i++)
		targets.push_back (params[i]);

	rts2db::TargetSet *tar_set = new rts2db::TargetSet ();
	try
	{
		tar_set->load (targets);
	}
	catch (...)
	{
		logStream (MESSAGE_ERROR) << "Sql Error" << sendLog;
		return;
	}

	i = 0;

	for (rts2db::TargetSet::iterator tar_iter = tar_set->begin(); tar_iter != tar_set->end (); tar_iter++)
	{
		JD = ln_get_julian_from_sys ();

		rts2db::Target *tar = (*tar_iter).second;

		XmlStream xs (&retVar);
		xs << *tar;

		// observations
		rts2db::ObservationSet obs_set;
		obs_set.loadTarget (tar->getTargetID ());
		int j = 0;
		for (rts2db::ObservationSet::iterator obs_iter = obs_set.begin(); obs_iter != obs_set.end(); obs_iter++, j++)
		{
			retVar["observation"][j]["obsid"] =  (*obs_iter).getObsId();
			retVar["observation"][j]["images"] = (*obs_iter).getNumberOfImages();
		}

		retVar["HOUR"] = tar->getHourAngle (JD);
		tar->sendInfo (xs, JD, 0);
		result[i++] = retVar;
	}
}
Ejemplo n.º 20
0
void TicketInfo::sessionExecute (XmlRpcValue& params, XmlRpcValue& result)
{
	if (params.size () != 1)
	{
		throw XmlRpcException ("Invalid number of parameters");
	}

	try
	{
		rts2sched::Ticket t = rts2sched::Ticket (params[0]);
		t.load ();
		XmlStream xs (&result);

		xs << t;
	}
	catch (rts2db::SqlError e)
	{
		throw XmlRpcException (e.what ());
	}
}
Ejemplo n.º 21
0
void ListTargets::sessionExecute (XmlRpcValue& params, XmlRpcValue& result)
{
	rts2db::TargetSet tar_set;

	if (params.size () == 1)
	{
		tar_set.loadByName (((std::string) params[0]).c_str ());
	}
	else
	{
		tar_set.load ();
	}

	double value;
	int i = 0;
	XmlRpcValue retVar;

	for (rts2db::TargetSet::iterator tar_iter = tar_set.begin(); tar_iter != tar_set.end (); tar_iter++, i++)
	{
		rts2db::Target *tar = (*tar_iter).second;
		retVar["id"] = tar->getTargetID ();
		retVar["type"] = tar->getTargetType ();
		if (tar->getTargetName ())
			retVar["name"] = tar->getTargetName ();
		else
			retVar["name"] = "NULL";

		retVar["enabled"] = tar->getTargetEnabled ();
		if (tar->getTargetComment ())
			retVar["comment"] = tar->getTargetComment ();
		else
			retVar["comment"] = "";
		value = tar->getLastObs();
		retVar["last_obs"] = value;
		struct ln_equ_posn pos;
		tar->getPosition (&pos, ln_get_julian_from_sys ());
		retVar["ra"] = pos.ra;
		retVar["dec"] = pos.dec;
		result[i++] = retVar;
	}
}
Ejemplo n.º 22
0
void XMLRPC2DIServer::xmlrpcval2amarg(XmlRpcValue& v, AmArg& a, 
				      unsigned int start_index) {
  if (v.valid()) {
    for (int i=start_index; i<v.size();i++) {
      switch (v[i].getType()) {
      case XmlRpcValue::TypeInt:   { /* DBG("X->A INT\n");*/ a.push(AmArg((int)v[i]));    }  break;
      case XmlRpcValue::TypeDouble:{ /* DBG("X->A DBL\n");*/ a.push(AmArg((double)v[i])); }  break;
      case XmlRpcValue::TypeString:{ /* DBG("X->A STR\n");*/ a.push(AmArg(((string)v[i]).c_str())); }  break;
      case XmlRpcValue::TypeArray: { 
	// DBG("X->A ARR\n"); 
	a.push(AmArg());
	a[a.size()-1].assertArray(0);
	AmArg arr; 
	xmlrpcval2amarg(v[i], a[a.size()-1], 0);
      } break;
	// TODO: support more types (datetime, struct, ...)
      default:     throw XmlRpcException("unsupported parameter type", 400);
      };
    }
  } 
}
bool XMLRPCManager::validateXmlrpcResponse(const std::string& method, XmlRpcValue &response,
                                    XmlRpcValue &payload)
{
  if (response.getType() != XmlRpcValue::TypeArray)
  {
    ROSCPP_LOG_DEBUG("XML-RPC call [%s] didn't return an array",
        method.c_str());
    return false;
  }
  if (response.size() != 3)
  {
    ROSCPP_LOG_DEBUG("XML-RPC call [%s] didn't return a 3-element array",
        method.c_str());
    return false;
  }
  if (response[0].getType() != XmlRpcValue::TypeInt)
  {
    ROSCPP_LOG_DEBUG("XML-RPC call [%s] didn't return a int as the 1st element",
        method.c_str());
    return false;
  }
  int status_code = response[0];
  if (response[1].getType() != XmlRpcValue::TypeString)
  {
    ROSCPP_LOG_DEBUG("XML-RPC call [%s] didn't return a string as the 2nd element",
        method.c_str());
    return false;
  }
  std::string status_string = response[1];
  if (status_code != 1)
  {
    ROSCPP_LOG_DEBUG("XML-RPC call [%s] returned an error (%d): [%s]",
        method.c_str(), status_code, status_string.c_str());
    return false;
  }
  payload = response[2];
  return true;
}
Ejemplo n.º 24
0
void DeviceState::sessionExecute (XmlRpcValue& params, XmlRpcValue& result)
{
	if (params.size () != 1)
	{
		throw XmlRpcException ("Invalid number of parameters");
	}
	HttpD *serv = (HttpD *) getMasterApp ();
	std::string p1 = std::string (params[0]);

	rts2core::Connection *conn;

	if (p1 == "centrald" || p1 == "")
		conn = *(serv->getCentraldConns ()->begin ());
	else
		conn = serv->getOpenConnection (p1.c_str ());

	if (conn == NULL)
	{
		throw XmlRpcException ("Cannot find specified device");
	}
	result[0] = conn->getStateString ();
	result[1] = (int) conn->getRealState ();
}
Ejemplo n.º 25
0
int main(int argc, char* argv[])
{
  string server = "localhost";
  string port = "11088";
  string service = def_service;
  string method = def_method;
  bool serviceSet = false;
  bool methodSet = false;
  int extraArgs = argc;

  // a kindergarten cmdline parser
  for (int i = 1; i < argc; ) {
    string arg = argv[i++];
    if (arg == "-h") {
      Usage();
    } else if (arg == "-d") {
      debug = true;
      quiet = false;
    } else if (arg == "-q") {
      quiet = true;
      debug = false;
    } else if (arg == "-s") {
      if (i >= argc) {
        cerr << "Error: -s missing hostname" << endl;
        Usage();
      } else {
        server = argv[i++];
      }
    } else if (arg == "-p") {
      if (i >= argc) {
        cerr << "Error: -p missing port number" << endl;
        Usage();
      } else {
        port = argv[i++];
      }
    } else if (arg[0] == '-') {
      cerr << "Error: don't understand flag '" << arg << "'" << endl;
      Usage();
    } else if ( ! serviceSet) {
      service = arg;
      method = def_method2;
      serviceSet = true;
    } else if ( ! methodSet) {
      method = arg;
      methodSet = true;
    } else {
      extraArgs = i - 1;
      break;
    }
  }

  int portnum = strtol(port.c_str(), NULL, 0);

  //XmlRpc::setVerbosity(5);
  cout << "Connecting to " << server << ":" << portnum << " ... " << flush;
  Tarati::Client client(server, portnum, debug);
  cout << "done" << endl;

  XmlRpcValue noArgs, result;

  try {
    if (service == "client") {
      if (method == "directory") {
        if (extraArgs != argc) {
          cerr << "Error: too many arguments on command line" << endl;
          Usage();
        }
        string service = "Server";
        string method = "ServiceDirectory";
        cout << "Service: " << service << "::" << method << "()" << endl;
        XmlRpcValue services;
        if (client.execute(service, method, noArgs, services)) {
          for (int i = 0; i < services.size(); i++) {
            XmlRpcValue version;
            string service = services[i];
            string method = "MethodDirectory";
            client.execute(service, "Version", noArgs, version);
            cout << "    Service: "
                 << service << "(v" << version << ")::"
                 << method << "()" << endl;
            XmlRpcValue methods;
            if (client.execute(service, method, noArgs, methods)) {
              for (int i = 0; i < methods.size(); i++) {
                cout << "        Method: " << methods[i] << endl;
              }
            }
          }
        }
      } else if (method == "stats") {
        if (extraArgs != argc) {
          cerr << "Error: too many arguments on command line" << endl;
          Usage();
        }
        string service = "Stats";
        string method = "States";
        cout << "Service: " << service << "::" << method << "()" << endl;
        XmlRpcValue states;
        if (client.execute(service, method, noArgs, states)) {
          for (int i = 0; i < states.size(); i++) {
            XmlRpcValue args = states[i];
            XmlRpcValue path;
            client.execute(service, "Path", args, path);
            XmlRpcValue name;
            client.execute(service, "Name", args, name);
            XmlRpcValue desc;
            client.execute(service, "Desc", args, desc);
            XmlRpcValue value;
            client.execute(service, "Value", args, value);
            cout << "    State:" << endl;
            cout << "        Path  = " << path << endl;
            cout << "        Name  = " << name << endl;
            cout << "        Desc  = " << desc << endl;
            cout << "        Value = " << value << endl;
          }
        }
      } else {
        cerr << "Don't understand "
             << service << "::" << method << "()" << endl;
      }
    } else {
      cout << "Service: " << service << "::" << method << "()" << endl;
      int arg = 0;
      XmlRpcValue args;
      for (int i = extraArgs; i < argc; i++) {
        // guess if the argument is numeric and convert if possible
        char * endptr;
        int value = strtol(argv[i], &endptr, 0);
        if (*(argv[i]) != '\0' && *endptr == '\0') {
          // treat as numeric
          args[arg++] = value;
        } else {
          // treat as string
          args[arg++] = argv[i];
        }
      }
      if (client.execute(service, method, args, result)) {
        cout << result << endl;
      }
    }
  } catch (const XmlRpcException& fault) {
    cout << "XML-RPC Error: " << fault.getMessage() << endl;
  }
  return 0;
}
Ejemplo n.º 26
0
Value toValue(XmlRpcValue& v, bool outer)
{
    int t = v.getType();
    switch (t) {
    case XmlRpcValue::TypeInt:
        return Value((int)v);
        break;
    case XmlRpcValue::TypeDouble:
        return Value((double)v);
        break;
    case XmlRpcValue::TypeString:
        {
            string s = (string)v;
            if (s.length()==0 || s[0]!='[') {
                return Value(s);
            } else {
                Value v;
                v.fromString(s.c_str());
                return v;
            }
        }
        break;
    case XmlRpcValue::TypeArray:
        {
            Value vbot;
            Bottle *bot = vbot.asList();
            for (int i=0; i<v.size(); i++) {
                XmlRpcValue& v2 = v[i];
                if (v2.getType()!=XmlRpcValue::TypeInvalid) {
                    Value v = toValue(v2,false);
                    if (i==0) {
                        std::string tag = v.asString();
                        if (tag=="list"||tag=="dict") {
                            if (!outer) {
                                bot->addString("list");
                            }
                        }
                    }
                    bot->add(v);
                }
            }
            return vbot;
        }
        break;
    case XmlRpcValue::TypeStruct:
        {
            Value vbot;
            Bottle *bot = vbot.asList();
            XmlRpcValue::ValueStruct& vals = v;
            bot->addString("dict");
            for (auto& val : vals) {
                XmlRpcValue& v2 = val.second;
                Bottle& sub = bot->addList();
                sub.addString(val.first.c_str());
                if (v2.getType()!=XmlRpcValue::TypeInvalid) {
                    sub.add(toValue(v2,false));
                }
            }
            return vbot;
        }
        break;
    case XmlRpcValue::TypeInvalid:
        return Value::getNullValue();
        break;
    }
    //printf("Skipping %d\n", t);
    return Value("(type not supported yet out of laziness)");
}
Ejemplo n.º 27
0
void ListPrettyValuesDevice::sessionExecute (XmlRpcValue& params, XmlRpcValue& result)
{
	HttpD *serv = (HttpD *) getMasterApp ();
	rts2core::Connection *conn;
	int i = 0;
	// print results for a single device..
	if (params.size() == 1)
	{
		if (((std::string) params[0]).length () == 0)
			conn = serv->getSingleCentralConn ();
		else
			conn = serv->getOpenConnection (((std::string)params[0]).c_str());
		if (!conn)
		{
			throw XmlRpcException ("Cannot get device " + (std::string) params[0]);
		}
		connectionValuesToXmlRpc (conn, result, true);
	}
	// print from all
	else
	{
		connections_t::iterator iter;
		rts2core::ValueVector::iterator variter;
		for (iter = serv->getCentraldConns ()->begin (); iter != serv->getCentraldConns ()->end (); iter++)
		{
			conn = *iter;
			std::string deviceName = (*iter)->getName ();
			// filter device list
			int v;
			for (v = 0; v < params.size (); v++)
			{
				if (((std::string) params[v]) == deviceName)
					break;
			}
			if (v == params.size ())
				continue;
			for (variter = conn->valueBegin (); variter != conn->valueEnd (); variter++, i++)
			{
				result[i] = deviceName + "." + (*variter)->getName ();
			}
		}
		for (iter = serv->getConnections ()->begin (); iter != serv->getConnections ()->end (); iter++)
		{
			conn = *iter;
			std::string deviceName = (*iter)->getName ();
			// filter device list
			int v;
			for (v = 0; v < params.size (); v++)
			{
				if (((std::string) params[v]) == deviceName)
					break;
			}
			if (v == params.size ())
				continue;
			for (variter = conn->valueBegin (); variter != conn->valueEnd (); variter++, i++)
			{
				result[i] = deviceName + "." + (*variter)->getName ();
			}
		}
	}
}
Ejemplo n.º 28
0
int main(int argc, char* argv[])
{
  if (argc != 3) {
    std::cerr << "Usage: HelloClient serverHost serverPort\n";
    return -1;
  }
  int port = atoi(argv[2]);
  //XmlRpc::setVerbosity(5);

  // Use introspection API to look up the supported methods
  XmlRpcClient c(argv[1], port);
  XmlRpcValue noArgs, result;
  for (int i = 0; i < 2000; i++)
  {
    if (c.execute("system.listMethods", noArgs, result))
      std::cout << "\nMethods:\n " << result << "\n\n";
    else
      std::cout << "Error calling 'listMethods'\n\n";
  }

  // Use introspection API to get the help string for the Hello method
  XmlRpcValue oneArg;
  oneArg[0] = "Hello";
  if (c.execute("system.methodHelp", oneArg, result))
    std::cout << "Help for 'Hello' method: " << result << "\n\n";
  else
    std::cout << "Error calling 'methodHelp'\n\n";

  // Call the Hello method
  if (c.execute("Hello", noArgs, result))
    std::cout << result << "\n\n";
  else
    std::cout << "Error calling 'Hello'\n\n";

  // Call the HelloName method
  oneArg[0] = "Chris";
  if (c.execute("HelloName", oneArg, result))
    std::cout << result << "\n\n";
  else
    std::cout << "Error calling 'HelloName'\n\n";

  // Add up an array of numbers
  XmlRpcValue numbers;
  numbers[0] = 33.33;
  numbers[1] = 112.57;
  numbers[2] = 76.1;
  std::cout << "numbers.size() is " << numbers.size() << std::endl;
  if (c.execute("Sum", numbers, result))
    std::cout << "Sum = " << double(result) << "\n\n";
  else
    std::cout << "Error calling 'Sum'\n\n";

  // Test the "no such method" fault
  if (c.execute("NoSuchMethod", numbers, result))
    std::cout << "NoSuchMethod call: fault: " << c.isFault() << ", result = " << result << std::endl;
  else
    std::cout << "Error calling 'Sum'\n";

  // Test the multicall method. It accepts one arg, an array of structs
  XmlRpcValue multicall;
  multicall[0][0]["methodName"] = "Sum";
  multicall[0][0]["params"][0] = 5.0;
  multicall[0][0]["params"][1] = 9.0;

  multicall[0][1]["methodName"] = "NoSuchMethod";
  multicall[0][1]["params"][0] = "";

  multicall[0][2]["methodName"] = "Sum";
  // Missing params

  multicall[0][3]["methodName"] = "Sum";
  multicall[0][3]["params"][0] = 10.5;
  multicall[0][3]["params"][1] = 12.5;

  if (c.execute("system.multicall", multicall, result))
    std::cout << "\nmulticall  result = " << result << std::endl;
  else
    std::cout << "\nError calling 'system.multicall'\n";

  return 0;
}