Example #1
0
void OnFaceDetection::callback() {
  /** Use a mutex to make it all thread safe. */
  AL::ALCriticalSection section(fCallbackMutex);
  try {
    /** Retrieve the data raised by the event. */
    fFaces = fMemoryProxy.getData("FaceDetected");
qiLogInfo("module.name") <<fFaces<<std::endl;
    /** Check that there are faces effectively detected. */
    if (fFaces.getSize() < 2 ) {
      if (fFacesCount != 0) {
        qiLogInfo("module.example") << "No face detected." << std::endl;
        fTtsProxy.say("No face detected.");
        fFacesCount = 0;
      }
	fTtsProxy.say("1 face.");
      return;
    }
    /** Check the number of faces from the FaceInfo field, and check that it has
    * changed from the last event.*/
    if (fFaces[1].getSize() - 1 != fFacesCount) {
      qiLogInfo("module.name") << fFaces[1].getSize() - 1 << " face(s) detected." << std::endl;
      char buffer[50];
      sprintf(buffer, "%d faces detected.", fFaces[1].getSize() - 1);
      fTtsProxy.say(std::string(buffer));
      /** Update the current number of detected faces. */
      fFacesCount = fFaces[1].getSize() - 1;
    }
  }
  catch (const AL::ALError& e) {
    qiLogError("module.name") << e.what() << std::endl;
  }
}
Example #2
0
 static void stop_handler(int signal_number)
 {
   qiLogVerbose() << "Signal " << signal_number << " received!";
   static int  count_int = 0;
   static int count_term = 0;
   int sigcount = 0;
   if (signal_number == SIGINT) {
     count_int++;
     sigcount = count_int;
   }
   else if (signal_number == SIGTERM) {
     count_term++;
     sigcount = count_term;
   }
   switch (sigcount) {
     case 1:
       qiLogInfo() << "Sending the stop command...";
       //register the signal again to call exit the next time if stop did not succeed
       Application::atSignal(boost::bind<void>(&stop_handler, _1), signal_number);
       // Stop might immediately trigger application destruction, so it has
       // to go after atSignal.
       Application::stop();
       return;
     default:
       //even for SIGTERM this is an error, so return 1.
       qiLogInfo() << "signal " << signal_number << " received a second time, calling exit(1).";
       exit(1);
       return;
   }
 }
Example #3
0
void SubscribeGyro::onMoveForward(const std::string &key, const AL::ALValue &value, const AL::ALValue &msg){
     AL::ALCriticalSection section(fCallbackMutex);
    gettimeofday(&currentTime);
    file << "Forward\t" << std::endl;
     bool test =  value;
	 timer();
     qiLogInfo("subscribegyro.gyroswing") << "Executing callback method on move forward: " << test  << std::endl;

   try {
       AL::ALProxy genericProxy ("MovementTools", "127.0.0.1" , 9559);
       genericProxy.callVoid("setSpeed", 0.8f);

 	 if (test == true && t > 300) {
		genericProxy.callVoid("swingForwards");

                qiLogInfo("subscribegyro.gyroswing") << "Forward! " << currentTime.tv_sec <<  std::endl;
		//qi::os::sleep(0.5);
		gettimeofday(&lastTime);
        }

    //fTtsProxy = AL::ALTextToSpeechProxy(getParentBroker());
    //fTtsProxy.say("Forward");
  }
  catch (const AL::ALError& e) {
    qiLogError("module.example") << e.what() << std::endl;
  }
}
Example #4
0
// define our callback function
void OnFaceDetection::callback() {

	// use a mutex to make this function thread safe
	AL::ALCriticalSection section(fCallbackMutex);

	try {

		// retrieves FaceDetected event data
		fFaces = fMemoryProxy.getData("FaceDetected");

		// check to see that there have been faces detected
		if(fFaces.getSize() < 2) {
			// if a face has been previously detected, by any thread, and now there are zero
			// faces detected, then advertise that the robot cannot see the person / people anymore
			if(fFaceCount != 0) {
				qiLogInfo("module.face") << "No faces detected" << std::endl;
				// fTextToSpeechProxy.say("Where. are. you? \\vct=5\\\\rspd=10\\\\pau=200\\I\\pau=50\\ am\\pau=50\\ coming\\pau=20\\ for\\pau=20\\ you.\\pau=1500\\ you\\pau=30\\ can\\pau=30\\ run\\pau=30\\ but\\pau=30\\ you\\pau=20\\ can't\\pau=30\\\\vct=1\\ hide");
				fTextToSpeechProxy.say("Hey! Where'd you \\vct=120\\go!?");
				fFaceCount = 0;
			}

			return;

		}

		// if we've gotten this far, then faces have been detected. Check info on them.
		// if the number / info on the face being detected has not changed, do nothing.
		if(fFaces[1].getSize() - 1 != fFaceCount) {
			
			qiLogInfo("module.face") << (fFaces[1].getSize() - 1) << " face(s) detected." << std::endl;
			
			if(fFaces[1].getSize() > 2) {
				char buffer[50];
				sprintf(buffer, "I see %d faces!", fFaces[1].getSize() - 1);
				fTextToSpeechProxy.say(std::string(buffer));
			}

			fTextToSpeechProxy.say("There you are!");

			// update the number of detected faces
			fFaceCount = fFaces[1].getSize() - 1;

		}

	} catch(const AL::ALError& error) {
		qiLogError("module.face") << error.what() << std::endl;
	}

}
Example #5
0
TEST_F(TestTask, ManyManyTasks)
{
  long long time = qi::os::ustime();
  unsigned NCLIENTS = 10;
  unsigned NTASKS = 10;
  if (getenv("NCLIENTS"))
    NCLIENTS = strtol(getenv("NCLIENTS"), 0, 0);
  if (getenv("NTASKS"))
    NTASKS = strtol(getenv("NTASKS"), 0, 0);
  unsigned TOTAL_CLIENTS = NTASKS * NCLIENTS;
  std::vector<Context> clients;
  for (unsigned i=0; i<NCLIENTS; ++i)
  {
    Context c;
    c.session = new qi::Session();
    c.session->connect(p.serviceDirectoryEndpoints()[0]);
    c.taskGenClient = c.session->service("taskGen");
    c.taskGenProxy = qi::Object<TaskGenerator>(taskGenClient);
    clients.push_back(c);
  }
  qiLogInfo() << "Setup clients: " << (qi::os::ustime() - time) << std::endl;
  time = qi::os::ustime();
  qi::Atomic<int> counter;
  for (unsigned i=0; i<NCLIENTS; ++i)
  {
    for (unsigned j=0; j<NTASKS; ++j)
    {
      qi::Object<Task> task = clients[i].taskGenProxy->newTask(
        boost::lexical_cast<std::string>(i*NTASKS + j));
      clients[i].tasks.push_back(task);
      task->onStep.connect(
        boost::bind(on_step, _1, boost::ref(counter)));
    }
  }
  ASSERT_EQ(NCLIENTS*NTASKS, taskGenProxy->taskCount());
  qiLogInfo() << "Setup tasks: " << (qi::os::ustime() - time) << std::endl;
  time = qi::os::ustime();
  taskGenProxy->step(1);
  for (unsigned step=0; step<1000 && *counter < TOTAL_CLIENTS; ++step)
    qi::os::msleep(5);
  ASSERT_EQ(*counter, TOTAL_CLIENTS);
  std::cerr << "Run: " << (qi::os::ustime() - time) << std::endl;
  // Teardown
  for (unsigned i=0; i<NCLIENTS; ++i)
  {
    delete clients[i].session;
  }
}
Example #6
0
  qi::Future<void> Session_SD::listenStandalone(const qi::Url &address)
  {
    if (_init)
      throw std::runtime_error("Already initialised");
    _init = true;
    _server->addObject(1, _serviceBoundObject);

    qiLogInfo() << "ServiceDirectory listener created on " << address.str();
    qi::Future<void> f = _server->listen(address);

    std::map<unsigned int, ServiceInfo>::iterator it =
        _sdObject->connectedServices.find(qi::Message::Service_ServiceDirectory);
    if (it != _sdObject->connectedServices.end())
    {
      it->second.setEndpoints(_server->endpoints());
      return f;
    }
    ServiceInfo si;
    si.setName("ServiceDirectory");
    si.setServiceId(qi::Message::Service_ServiceDirectory);
    si.setMachineId(qi::os::getMachineId());
    si.setProcessId(qi::os::getpid());
    si.setSessionId("0");
    si.setEndpoints(_server->endpoints());
    unsigned int regid = _sdObject->registerService(si);
    (void)regid;
    _sdObject->serviceReady(qi::Message::Service_ServiceDirectory);
    //serviceDirectory must have id '1'
    assert(regid == qi::Message::Service_ServiceDirectory);

    _server->_server.endpointsChanged.connect(boost::bind(&Session_SD::updateServiceInfo, this));

    return f;
  }
Example #7
0
  bool ParameterModel::addChoice(ChoiceModelPtr choice)
  {
    qiLogDebug() << "addChoice function" << std::endl;
    Signature signature(_p->_metaProperty.signature());

    //if false choice and parameter are the same type
    if(Signature(choice->value().signature()).isConvertibleTo(signature) < 1.0f )
    {
      qiLogWarning() << "choice.type (i.e "
                     << choice->value().signature().toString()
                     << ") != parameter.type (i.e "
                     << _p->_defaultValue.signature().toString()
                     <<")"
                     << std::endl;
      return false;
    }

    //If choice.value is not in [parameter.min, paramater.max] then the choice
    //is incorrect
    if(!_p->inInterval(choice->value(),
                       _p->_min,
                       _p->_max)
       )
    {
      qiLogInfo()    << "Choice : is not in interval"
                     << std::endl;
      return false;
    }

    _p->_choices.push_front(choice);
    return true;
  }
Example #8
0
std::string reply(const std::string &msg, const float &value) {
    qiLogInfo() << "Message recv:" << msg << " * " << value;
    std::stringstream ss;

    ss << msg << value;
    return ss.str();
}
Example #9
0
 void ServiceDirectory::onSocketDisconnected(TransportSocketPtr socket, std::string error)
 {
   boost::recursive_mutex::scoped_lock lock(mutex);
   // clean from idxToSocket
   for (std::map<unsigned int, TransportSocketPtr>::iterator it = idxToSocket.begin(), iend = idxToSocket.end(); it != iend;)
   {
     std::map<unsigned int, TransportSocketPtr>::iterator next = it;
     ++next;
     if (it->second == socket)
       idxToSocket.erase(it);
     it = next;
   }
   // if services were connected behind the socket
   std::map<TransportSocketPtr, std::vector<unsigned int> >::iterator it;
   it = socketToIdx.find(socket);
   if (it == socketToIdx.end()) {
     return;
   }
   // Copy the vector, iterators will be invalidated.
   std::vector<unsigned int> ids = it->second;
   // Always start at the beginning since we erase elements on unregisterService
   // and mess up the iterator
   for (std::vector<unsigned int>::iterator it2 = ids.begin();
        it2 != ids.end();
        ++it2)
   {
     qiLogInfo() << "Service #" << *it2 << " disconnected";
     try {
       unregisterService(*it2);
     } catch (std::runtime_error &) {
       qiLogWarning() << "Cannot unregister service #" << *it2;
     }
   }
   socketToIdx.erase(it);
 }
Example #10
0
void Bumper::onRightBumperPressed() {

  std::cout<<"onRightBumperPressed()"<<std::endl;

  qiLogInfo("module.example") << "Executing callback method on right bumper event" << std::endl;
  /**
  * As long as this is defined, the code is thread-safe.
  */
  AL::ALCriticalSection section(fCallbackMutex);

  /**
  * Check that the bumper is pressed.
  */
std::cout<<"before memory.getData2"<<std::endl;
  fState =  fMemoryProxy.getData("RightBumperPressed");
std::cout<<"After memory.getData2"<<std::endl;

  if (fState  > 0.5f) {
	std::cout<<"if"<<std::endl;
    return;
  }
  try {
    fTtsProxy = AL::ALTextToSpeechProxy(getParentBroker());
	std::cout<<"HELLO"<<std::endl;
    fTtsProxy.say("Hello!");
  }
  catch (const AL::ALError& e) {
    qiLogError("module.example") << e.what() << std::endl;
  }
std::cout<<"END"<<std::endl;
}
Example #11
0
 // Find out our async parent and add to it
 static bool insertAsyncParentTrace(CallList& l, CallData* d)
 {
   if (l.empty())
   {
     qiLogDebug() << "empty";
     return false;
   }
   qiLogDebug() << l.front()->tStart;
   // Get first entry that started after our post time.
   CallList::iterator it = std::upper_bound(l.begin(), l.end(), CallTime(d->tPost));
   if (it == l.begin())
   { // damm, first element is older than us
     qiLogInfo() << "No async parent can be found";
     return false;
   }
   --it;
   qiLogDebug() << "Child check";
   // try if a sync child is better placed than it
   bool wasInserted = insertAsyncParentTrace((*it)->children, d);
   if (wasInserted)
     return true;
   // was not inserted in children, insert here
   (*it)->asyncChildren.push_back(d);
   d->asyncParent = *it;
   return true;
 }
Example #12
0
std::string reply(const int &msg) {
    qiLogInfo() << "Message recv:" << msg;
    std::stringstream ss;

    ss << msg << "bim";
    return ss.str();
}
Example #13
0
SigGenerator::SigGenerator(int min_deep, int max_deep, int max_tuple_size)
    : min_deep(min_deep)
    , max_deep(max_deep)
    , max_tuple_size(max_tuple_size)
    , current_deep(0)
{
    qiLogInfo("core.longtermTest") << "signature generator engaged" << std::endl;
}
Example #14
0
void ping()
{
  while (true)
  {
    qiLogInfo("test.dump") << "ping";
    qi::os::msleep(900);
  }
}
Example #15
0
qi::Future<void> TestImpl::saySlowerButBetter(const std::string& mess)
{
  qiLogInfo() << "Saying " << mess << " slowly";
  assert(!_boole.swap(true));

  qi::sleepFor(qi::Seconds(1));

  ++_numberOfSay;
  message.set(mess);
  onSayMessage(_numberOfSay);

  qiLogInfo() << "Middle say";

  assert(_boole.swap(false));
  return qi::asyncDelay([]{
        qiLogInfo() << "End say";
      }, qi::Seconds(1));
}
Example #16
0
string tulingModule::getResponse(string text)
{
    static int index=0;
    if(text == ""){
        return string("不好意思,我没有听清楚你说的话^startTag(not know),您可以再说一遍么?");
    }
    string cmd = "curl -G http://www.tuling123.com/openapi/api -d key=c237b459589ef904699807b7dadcc300 -d info="+text+"/";

    string result = exec_shell(cmd);
    string rec_result;

    qiLogInfo("Result From Tuling:")<<result<<std::endl;
    std::string loc = "\"text\"";
    int ind_e = result.find(loc);
    while(result[ind_e] != ':'){
        ind_e++;
    }
    while(result[ind_e] != '"'){
        if(result[ind_e] == '}'){
            rec_result = "";
            return rec_result;
        }
        ind_e++;
    }
    int ind_s = ++ind_e;
    while(result[ind_e] != '"'){
        ind_e++;
    }
    rec_result = result.substr(ind_s, ind_e-ind_s);

    //char* expr = "animations/Stand/BodyTalk/BodyTalk_";
    char* expr = "animations/Stand/Gestures/Explain_";
    char buffer[2000];

    sprintf(buffer, "^start(%s%d)%s", expr, index%12, rec_result.c_str());
    index++;

    qiLogInfo("Result From Tuling:")<<string(buffer)<<std::endl;

    return string(buffer);
}
Example #17
0
/**
 * @brief 
 */
void oru_walk::initPosition()
{
    /// @attention Hardcoded parameter!
    unsigned int init_time = 1200;


    ALValue initPositionCommands;

    initPositionCommands.arraySetSize(6);
    initPositionCommands[0] = string("jointActuator");
    initPositionCommands[1] = string("ClearAll");
    initPositionCommands[2] = string("time-separate");
    initPositionCommands[3] = 0;
    initPositionCommands[4].arraySetSize(1);
    initPositionCommands[5].arraySetSize(JOINTS_NUM);
    for (int i = 0; i < JOINTS_NUM; i++)
    {
        initPositionCommands[5][i].arraySetSize(1);
    }
    initJointAngles (initPositionCommands[5]);
    for (int i = 0; i < LOWER_JOINTS_NUM; i++)
    {
        ref_joint_angles[i] = initPositionCommands[5][i][0];
    }



    // set time
    try
    {
        initPositionCommands[4][0] = dcm_proxy->getTime(init_time);
    }
    catch (const ALError &e)
    {
        ORUW_THROW_ERROR("Error on DCM getTime : ", e);
    }


    // send commands
    try
    {
        dcm_proxy->setAlias(initPositionCommands);
    }
    catch (const AL::ALError &e)
    {
        ORUW_THROW_ERROR("Error with DCM setAlias : ", e);
    }

    qi::os::msleep(init_time);
    qiLogInfo ("module.oru_walk", "Execution of initPosition() is finished.");
}
Example #18
0
  unsigned int ServiceDirectory::registerService(const ServiceInfo &svcinfo)
  {
    boost::shared_ptr<ServiceBoundObject> sbo = serviceBoundObject.lock();
    if (!sbo)
      throw std::runtime_error("ServiceBoundObject has expired.");

    TransportSocketPtr socket = sbo->currentSocket();
    boost::recursive_mutex::scoped_lock lock(mutex);
    std::map<std::string, unsigned int>::iterator it;
    it = nameToIdx.find(svcinfo.name());
    if (it != nameToIdx.end())
    {
      std::stringstream ss;
      ss << "Service \"" <<
        svcinfo.name() <<
        "\" (#" << it->second << ") is already registered. " <<
        "Rejecting conflicting registration attempt.";
      qiLogWarning()  << ss.str();
      throw std::runtime_error(ss.str());
    }

    unsigned int idx = ++servicesCount;
    nameToIdx[svcinfo.name()] = idx;
    // Do not add serviceDirectory on the map (socket() == null)
    if (idx != qi::Message::Service_ServiceDirectory)
      socketToIdx[socket].push_back(idx);
    pendingServices[idx] = svcinfo;
    pendingServices[idx].setServiceId(idx);
    idxToSocket[idx] = socket;

    std::stringstream ss;
    ss << "Registered Service \"" << svcinfo.name() << "\" (#" << idx << ")";
    if (! svcinfo.name().empty() && svcinfo.name()[0] == '_') {
      // Hide services whose name starts with an underscore
      qiLogDebug() << ss.str();
    }
    else
    {
      qiLogInfo() << ss.str();
    }

    qi::UrlVector::const_iterator jt;
    for (jt = svcinfo.endpoints().begin(); jt != svcinfo.endpoints().end(); ++jt)
    {
      qiLogDebug() << "Service \"" << svcinfo.name() << "\" is now on " << jt->str();
    }

    return idx;
  }
Example #19
0
void OnFaceDetection::init() {
  try {
    /** See if there is any face already detected at initialization. */
    fFaces = fMemoryProxy.getData("FaceDetected");
    if (fFaces.getSize() < 2) {
      qiLogInfo("module.example") << "No face detected." << std::endl;
      fTtsProxy.say("No face detected");
    }
    /** Subscribe to the event FaceDetected, with appropriate callback function. */
    fMemoryProxy.subscribeToEvent("FaceDetected", "OnFaceDetection", "callback");
  }
  catch (const AL::ALError& e) {
    qiLogError("module.name") << e.what() << std::endl;
  }
}
Example #20
0
 void MessageDispatcher::sent(const qi::Message& msg) {
   //store Call id, we can use them later to notify the client
   //if the call did not succeed. (network disconnection, message lost)
   if (msg.type() == qi::Message::Type_Call)
   {
     boost::mutex::scoped_lock l(_messageSentMutex);
     MessageSentMap::iterator it = _messageSent.find(msg.id());
     if (it != _messageSent.end()) {
       qiLogInfo() << "Message ID conflict. A message with the same Id is already in flight" << msg.id();
       return;
     }
     _messageSent[msg.id()] = msg.address();
   }
   return;
 }
Example #21
0
/**
 * @brief Set stiffness of joints.
 *
 * @param[in] stiffnessValue value of stiffness [0;1]
 */
void oru_walk::setStiffness(const float &stiffnessValue)
{
    ALValue stiffnessCommands;


    if ((stiffnessValue < 0) || (stiffnessValue > 1))
    {
        ORUW_THROW("Wrong parameters");
    }


    // Prepare one dcm command:
    // it will linearly "Merge" all joint stiffness
    // from last value to "stiffnessValue" in 1 seconde
    stiffnessCommands.arraySetSize(3);
    stiffnessCommands[0] = std::string("jointStiffness");
    stiffnessCommands[1] = std::string("Merge");
    stiffnessCommands[2].arraySetSize(1);
    stiffnessCommands[2][0].arraySetSize(2);
    stiffnessCommands[2][0][0] = stiffnessValue;


    /// @attention Hardcoded parameter!
    unsigned int stiffness_change_time = 1000;
    try
    {
        stiffnessCommands[2][0][1] = dcm_proxy->getTime(stiffness_change_time);
    }
    catch (const ALError &e)
    {
        ORUW_THROW_ERROR("Error on DCM getTime : ", e);
    }


    try
    {
        dcm_proxy->set(stiffnessCommands);
    }
    catch (const ALError &e)
    {
        ORUW_THROW_ERROR("Error when sending stiffness to DCM : ", e);
    }

    qi::os::msleep(stiffness_change_time);
    qiLogInfo ("module.oru_walk", "Execution of setStiffness() is finished.");
}
Example #22
0
  //we ensure in that function that connect to all events are already setup when we said we are connect.
  //that way we can't be connected without being fully ready.
  qi::FutureSync<void> ServiceDirectoryClient::connect(const qi::Url &serviceDirectoryURL) {
    if (isConnected()) {
      const char* s = "Session is already connected";
      qiLogInfo() << s;
      return qi::makeFutureError<void>(s);
    }
    _sdSocket = qi::makeTransportSocket(serviceDirectoryURL.protocol());
    if (!_sdSocket)
      return qi::makeFutureError<void>(std::string("unrecognized protocol '") + serviceDirectoryURL.protocol() + "' in url '" + serviceDirectoryURL.str() + "'");
    _sdSocketDisconnectedSignalLink = _sdSocket->disconnected.connect(&ServiceDirectoryClient::onSocketDisconnected, this, _1);
    _remoteObject.setTransportSocket(_sdSocket);

    qi::Promise<void> promise;
    qi::Future<void> fut = _sdSocket->connect(serviceDirectoryURL);
    fut.connect(&ServiceDirectoryClient::onSocketConnected, this, _1, promise);
    return promise.future();
  }
Example #23
0
 TestTask()
 {
   static bool init = false;
   static qi::AnyObject tgs;
   if (!init)
   {
     std::vector<std::string> objs = qi::loadObject("task");
     qiLogInfo() << "loadobject gave " << objs.size();
     if (objs.size() != 1)
       throw std::runtime_error("Expected one object in taskService");
     tgs = qi::createObject("TaskGenerator");
     if (!tgs)
       throw std::runtime_error("No TaskGenerator service found");
     init = true;
   }
   taskGenService = tgs;
 }
Example #24
0
  qi::Future<void> Session_SD::listenStandalone(const std::vector<qi::Url> &listenAddresses)
  {
    if (_init)
      throw std::runtime_error("Already initialised");
    _init = true;
    _server->addObject(1, _serviceBoundObject);

    std::ostringstream messInfo;
    messInfo << "ServiceDirectory listener created on";
    qi::FutureBarrier<void> barrier;
    for (const qi::Url& url : listenAddresses)
    {
      messInfo << " " << url.str();
      barrier.addFuture(_server->listen(url));
    }
    qiLogInfo() << messInfo.str();
    qi::Promise<void> prom;
    qi::adaptFuture(barrier.future(), prom);
    qi::Future<void> f = prom.future();

    std::map<unsigned int, ServiceInfo>::iterator it =
        _sdObject->connectedServices.find(qi::Message::Service_ServiceDirectory);
    if (it != _sdObject->connectedServices.end())
    {
      it->second.setEndpoints(_server->endpoints());
      return f;
    }
    ServiceInfo si;
    si.setName("ServiceDirectory");
    si.setServiceId(qi::Message::Service_ServiceDirectory);
    si.setMachineId(qi::os::getMachineId());
    si.setProcessId(qi::os::getpid());
    si.setSessionId("0");
    si.setEndpoints(_server->endpoints());
    unsigned int regid = _sdObject->registerService(si);
    (void)regid;
    _sdObject->serviceReady(qi::Message::Service_ServiceDirectory);
    //serviceDirectory must have id '1'
    QI_ASSERT(regid == qi::Message::Service_ServiceDirectory);

    _server->_server.endpointsChanged.connect(boost::bind(&Session_SD::updateServiceInfo, this));

    return f;
  }
Example #25
0
// define init method
void OnFaceDetection::init() {

	try {

		// check to see if there are faces present at module initialization
		fFaces = fMemoryProxy.getData("FaceDetected");

		if(fFaces.getSize() < 2) {
			qiLogInfo("module.face") << "No faces detected" << std::endl;
			fTextToSpeechProxy.say("I... can't... see you.");
		}

		// subscribe to "FaceDetected" event, with the appropriate callback function
		fMemoryProxy.subscribeToEvent("FaceDetected", "OnFaceDetection", "callback");

	} catch(const AL::ALError& error) {
		qiLogError("module.face") << error.what() << std::endl;
	}

}
Example #26
0
  qi::FutureSync<void> SessionPrivate::connect(const qi::Url &serviceDirectoryURL)
  {
    if (isConnected()) {
      const char* s = "Session is already connected";
      qiLogInfo() << s;
      return qi::makeFutureError<void>(s);
    }
    _serverObject.open();
    //add the servicedirectory object into the service cache (avoid having
    // two remoteObject registered on the same transportSocket)
    _serviceHandler.addService("ServiceDirectory", _sdClient.object());
    _socketsCache.init();

    qi::Future<void> f = _sdClient.connect(serviceDirectoryURL);
    qi::Promise<void> p;

    // go through hoops to get shared_ptr on this
    f.connect(&SessionPrivate::addSdSocketToCache, this, _1, serviceDirectoryURL, p);
    return p.future();
  }
Example #27
0
int main(int argc, char *argv[])
{
  qi::Application app(argc, argv);

#if defined(WITH_BREAKPAD) && defined(GATEWAY_BUILD_TAG)
  BreakpadExceptionHandler eh(BREAKPAD_DUMP_DIR);
  eh.setBuildTag(GATEWAY_BUILD_TAG);
  qiLogInfo() << "Build tag: " GATEWAY_BUILD_TAG;
#endif


  // declare the program options
  po::options_description desc("Usage:\n  qi-service masterAddress [options]\nOptions");
  desc.add_options()
      ("help", "Print this help.")
      ("qi-url",
       po::value<std::string>()->default_value(std::string("tcp://127.0.0.1:9559")),
       "The master address")
      ("qi-listen-url",
       po::value<std::string>()->default_value(std::string("tcp://0.0.0.0:9559")),
       "The gateway address")
      ("gateway-type",
       po::value<std::string>()->default_value(std::string("local")),
       "The gateway type");

  // allow master address to be specified as the first arg
  po::positional_options_description pos;
  pos.add("master-address", 1);

  // parse and store
  po::variables_map vm;
  try
  {
    po::store(po::command_line_parser(argc, argv).
              options(desc).positional(pos).run(), vm);
    po::notify(vm);

    if (vm.count("help"))
    {
      std::cout << desc << "\n";
      return EXIT_SUCCESS;
    }

    const std::string gatewayAddress = vm["qi-listen-url"].as<std::string>();
    const std::string masterAddress = vm["qi-url"].as<std::string>();
    const std::string gatewayType = vm["gateway-type"].as<std::string>();

    if (gatewayType == "local")
    {
      qi::Gateway gateway;
      bool ok = false;
      for (unsigned i = 0; i < NB_RETRY_RECONNECT && !(ok = attachToServiceDirectory(gateway, qi::Url(masterAddress))); ++i)
      {
        qiLogInfo() << "Connection to SD failed, retrying in 2 seconds";
        qi::sleepFor(RETRY_RECONNECT_WAIT);
      }
      if (!ok || !gateway.listen(gatewayAddress))
      {
        qiLogError() << "Failed to launch gateway.";
        return EXIT_FAILURE;
      }
      qiLogInfo() << "Local gateway ready: " << gatewayAddress << std::endl;
      app.run();
    }
    else if (gatewayType == "remote")
    {
      qiLogError() << "Not implemented";
      return EXIT_FAILURE;
    }
    else if (gatewayType == "reverse")
    {
      qiLogError() << "Not implemented";
      return EXIT_FAILURE;
    }
    else
    {
      qiLogError() << "unknown type: " << gatewayType;
      return EXIT_FAILURE;
    }
  }
  catch (const boost::program_options::error&)
  {
    qiLogError() << desc;
  }

  return EXIT_SUCCESS;
}
Example #28
0
void cb(std::string s)
{
  qiLogInfo() << "callback: said " << s;
}
Example #29
0
std::string reply(const std::string &msg) {
    qiLogInfo() << "Message recv:" << msg;
    return msg + "bim";
}
Example #30
0
qi::AnyValue reply(const qi::AnyValue &myval) {
    static int i = 0;
    qi::AnyReference val = qi::AnyReference::from(myval);
    qiLogInfo() << i++ << " Message received with the signature: " << myval.signature(false).toString() << " = " << qi::encodeJSON(val) << std::endl;
    return myval;
}