Пример #1
0
int main(int argc, char** argv)
{
  // set up our simpleConnector
  ArSimpleConnector simpleConnector(&argc, argv);
  // robot
  ArRobot robot;
  // a key handler so we can do our key handling
  ArKeyHandler keyHandler;

  ArLog::init(ArLog::StdOut,ArLog::Verbose);

  // if there are more arguments left then it means we didn't
  // understand an option
  if (!simpleConnector.parseArgs() || argc > 1)
  {    
    simpleConnector.logOptions();
    keyHandler.restore();
    exit(1);
  }

  // mandatory init
  Aria::init();
  ArLog::init(ArLog::StdOut, ArLog::Terse, NULL, true);

  // let the global aria stuff know about it
  Aria::setKeyHandler(&keyHandler);
  // toss it on the robot
  robot.attachKeyHandler(&keyHandler);

  // set up the robot for connecting
  if (!simpleConnector.connectRobot(&robot))
  {
    printf("Could not connect to robot... exiting\n");
    Aria::shutdown();
    keyHandler.restore();
    return 1;
  }

  // turn on the motors for the velocity response test
  robot.comInt(ArCommands::ENABLE, 1);
  velTime.setToNow();

  // turn off the sonar
  robot.comInt(ArCommands::SONAR, 0);

  ArGlobalFunctor1<ArRobot *> userTaskCB(&userTask, &robot);
  robot.addUserTask("iotest", 100, &userTaskCB);

  robot.comInt(ArCommands::IOREQUEST, 1);
  requestTime.setToNow();

  //start the robot running, true so that if we lose connection the run stops
  robot.run(true);
  
  // now exit
  Aria::shutdown();
  return 0;


}
int main(int argc, char **argv)
{

  Aria::init();

  ArArgumentParser parser(&argc, argv);
  // set up our simple connector
  ArSimpleConnector simpleConnector(&parser);  
  ArRobot robot;

  // set up the robot for connecting
  if (!simpleConnector.connectRobot(&robot))
  {
    printf("Could not connect to robot... exiting\n");
    Aria::exit(1);
  }

  robot.runAsync(true);

  ArModuleLoader::Status status;
  std::string str;

  ArLog::log(ArLog::Terse, "moduleActionExample: Loading the module \"moduleActionExample_Mod\" with a string argument...");
  status=ArModuleLoader::load("./moduleActionExample_Mod", &robot, (char *)"You've loaded a module!");
  printStatus(status);

  ArLog::log(ArLog::Terse, "moduleActionExample: Loading the module \"moduleActionExample_Mod2\" with a string argument...");
  status=ArModuleLoader::load("./moduleActionExample2_Mod", &robot, (char *)"You've loaded a second module!");
  printStatus(status);

  //ArLog::log(ArLog::Terse, "moduleActionExample: Reloading \"moduleActionExample_Mod\" with no argument...");
  //status=ArModuleLoader::reload("./moduleActionExample_Mod", &robot);
  //printStatus(status);

  //ArLog::log(ArLog::Terse, "moduleActionExample: Closing  \"moduleActionExample_Mod\"...");
  //status=ArModuleLoader::close("./moduleActionExample_Mod");
  //printStatus(status);

  ArUtil::sleep(3000);

  Aria::exit(0);
  return(0);
}
Пример #3
0
int main(int argc, char **argv)
{
    Aria::init();
    //ArLog::init(ArLog::StdOut, ArLog::Verbose);
    // robot
    ArRobot robot;
    /// our server
    ArServerBase server;

    // set up our parser
    ArArgumentParser parser(&argc, argv);
    // set up our simple connector
    ArSimpleConnector simpleConnector(&parser);

    // set up a gyro
    ArAnalogGyro gyro(&robot);

    // load the default arguments
    parser.loadDefaultArguments();

    // parse the command line... fail and print the help if the parsing fails
    // or if the help was requested
    if (!simpleConnector.parseArgs() || !parser.checkHelpAndWarnUnparsed())
    {
        simpleConnector.logOptions();
        exit(1);
    }

    if (!server.loadUserInfo("userServerTest.userInfo"))
    {
        printf("Could not load user info, exiting\n");
        exit(1);
    }

    server.logUsers();

    // first open the server up
    if (!server.open(7272))
    {
        printf("Could not open server port\n");
        exit(1);
    }

    // sonar, must be added to the robot
    ArSonarDevice sonarDev;
    // add the sonar to the robot
    robot.addRangeDevice(&sonarDev);

    ArIRs irs;
    robot.addRangeDevice(&irs);

    ArBumpers bumpers;
    robot.addRangeDevice(&bumpers);

    // a laser in case one is used
    ArSick sick(361, 180);
    // add the laser to the robot
    robot.addRangeDevice(&sick);




    // attach stuff to the server
    ArServerInfoRobot serverInfoRobot(&server, &robot);
    ArServerInfoSensor serverInfoSensor(&server, &robot);
    ArServerInfoDrawings drawings(&server);
    drawings.addRobotsRangeDevices(&robot);

    // ways of moving the robot
    ArServerModeStop modeStop(&server, &robot);
    ArServerModeDrive modeDrive(&server, &robot);
    ArServerModeRatioDrive modeRatioDrive(&server, &robot);
    ArServerModeWander modeWander(&server, &robot);
    modeStop.addAsDefaultMode();
    modeStop.activate();

    // set up the simple commands
    ArServerHandlerCommands commands(&server);
    // add the commands for the microcontroller
    ArServerSimpleComUC uCCommands(&commands, &robot);
    // add the commands for logging
    ArServerSimpleComMovementLogging loggingCommands(&commands, &robot);
    // add the commands for the gyro
    ArServerSimpleComGyro gyroCommands(&commands, &robot, &gyro);

    // add the commands to enable and disable safe driving to the simple commands
    modeDrive.addControlCommands(&commands);

    // Forward any video if we have some to forward.. this will forward
    // from SAV or ACTS, you can find both on our website
    // http://robots.activmedia.com, ACTS is for color tracking and is
    // charged for but SAV just does software A/V transmitting and is
    // free to all our customers... just run ACTS or SAV before you
    // start this program and this class here will forward video from it
    // to MobileEyes
    ArHybridForwarderVideo videoForwarder(&server, "localhost", 7070);

    // make a camera to use in case we have video
    ArPTZ *camera = NULL;
    ArServerHandlerCamera *handlerCamera = NULL;
    // if we have video then set up a camera
    if (videoForwarder.isForwardingVideo())
    {
        bool invertedCamera = false;
        camera = new ArVCC4(&robot,	invertedCamera,
                            ArVCC4::COMM_UNKNOWN, true, true);
        camera->init();
        handlerCamera = new ArServerHandlerCamera(&server, &robot, camera);
    }

    server.logCommandGroups();
    server.logCommandGroupsToFile("userServerTest.commandGroups");

    // now let it spin off in its own thread
    server.runAsync();

    // set up the robot for connecting
    if (!simpleConnector.connectRobot(&robot))
    {
        printf("Could not connect to robot... exiting\n");
        Aria::shutdown();
        return 1;
    }

    // set up the laser before handing it to the laser mode
    simpleConnector.setupLaser(&sick);

    robot.enableMotors();
    // start the robot running, true so that if we lose connection the run stops
    robot.runAsync(true);

    sick.runAsync();

    // connect the laser if it was requested
    if (!simpleConnector.connectLaser(&sick))
    {
        printf("Could not connect to laser... exiting\n");
        Aria::shutdown();
        return 1;
    }

    robot.waitForRunExit();
    // now exit
    Aria::shutdown();
    exit(0);
}
int main(int argc, char **argv)
{
  Aria::init();
  ArRobot robot;
  ArServerBase server;

  ArArgumentParser parser(&argc, argv);
  ArSimpleConnector simpleConnector(&parser);
  ArServerSimpleOpener simpleOpener(&parser);


  // parse the command line... fail and print the help if the parsing fails
  // or if help was requested
  parser.loadDefaultArguments();
  if (!simpleConnector.parseArgs() || !simpleOpener.parseArgs() || 
      !parser.checkHelpAndWarnUnparsed())
  {    
    simpleConnector.logOptions();
    simpleOpener.logOptions();
    exit(1);
  }

  // Set up where we'll look for files such as config file, user/password file,
  // etc.
  char fileDir[1024];
  ArUtil::addDirectories(fileDir, sizeof(fileDir), Aria::getDirectory(), 
			 "ArNetworking/examples");

  // first open the server up
  if (!simpleOpener.open(&server, fileDir, 240))
  {
    if (simpleOpener.wasUserFileBad())
      printf("Error: Bad user/password/permissions file.\n");
    else
      printf("Error: Could not open server port. Use -help to see options.\n");
    exit(1);
  }


  // Devices
  ArAnalogGyro gyro(&robot);

  ArSonarDevice sonarDev;
  robot.addRangeDevice(&sonarDev);

  ArIRs irs;
  robot.addRangeDevice(&irs);

  ArBumpers bumpers;
  robot.addRangeDevice(&bumpers);

  ArSick sick(361, 180);
  robot.addRangeDevice(&sick);  
  

  ArServerInfoRobot serverInfoRobot(&server, &robot);
  ArServerInfoSensor serverInfoSensor(&server, &robot);

  // This is the service that provides drawing data to the client.
  ArServerInfoDrawings drawings(&server);

  // Convenience function that sets up drawings for all the robot's current
  // range devices (using default shape and color info)
  drawings.addRobotsRangeDevices(&robot);

  // Add our custom drawings
  drawings.addDrawing(
      //                shape:      color:               size:   layer:
      new ArDrawingData("polyLine", ArColor(255, 0, 0),  2,      49),
      "exampleDrawing_Home", 
      new ArGlobalFunctor2<ArServerClient*, ArNetPacket*>(&exampleHomeDrawingNetCallback)
  );
  drawings.addDrawing(                                    
      new ArDrawingData("polyDots", ArColor(0, 255, 0), 250, 48),
      "exampleDrawing_Dots", 
      new ArGlobalFunctor2<ArServerClient*, ArNetPacket*>(&exampleDotsDrawingNetCallback)
  );
  drawings.addDrawing(
      new ArDrawingData("polySegments", ArColor(0, 0, 0), 4, 52),
      "exampleDrawing_XMarksTheSpot", 
      new ArGlobalFunctor2<ArServerClient*, ArNetPacket*>(&exampleXDrawingNetCallback)
  );
  drawings.addDrawing(
      new ArDrawingData("polyArrows", ArColor(255, 0, 255), 500, 100),
      "exampleDrawing_Arrows", 
      new ArGlobalFunctor2<ArServerClient*, ArNetPacket*>(&exampleArrowsDrawingNetCallback)
  );

  // modes for moving the robot
  ArServerModeStop modeStop(&server, &robot);
  ArServerModeDrive modeDrive(&server, &robot);
  ArServerModeRatioDrive modeRatioDrive(&server, &robot);
  ArServerModeWander modeWander(&server, &robot);
  modeStop.addAsDefaultMode();
  modeStop.activate();

  

  // Connect to the robot.
  if (!simpleConnector.connectRobot(&robot))
  {
    printf("Error: Could not connect to robot... exiting\n");
    Aria::shutdown();
    return 1;
  }

  // set up the laser before handing it to the laser mode
  simpleConnector.setupLaser(&sick);

  robot.enableMotors();

  // start the robot cycle running in a background thread
  robot.runAsync(true);

  // start the laser processing cycle in a background thread
  sick.runAsync();

  // connect the laser if it was requested
  if (!simpleConnector.connectLaser(&sick))
  {
    printf("Error: Could not connect to laser... exiting\n");
    Aria::shutdown();
    return 1;
  }

  // log whatever we wanted to before the runAsync
  simpleOpener.checkAndLog();

  // run the server thread in the background
  server.runAsync();

  printf("Server is now running...\n");


  // Add a key handler mostly that windows can exit by pressing
  // escape, note that the key handler prevents you from running this program
  // in the background on Linux.
  ArKeyHandler *keyHandler;
  if ((keyHandler = Aria::getKeyHandler()) == NULL)
  {
    keyHandler = new ArKeyHandler;
    Aria::setKeyHandler(keyHandler);
    robot.lock();
    robot.attachKeyHandler(keyHandler);
    robot.unlock();
    printf("To exit, press escape.\n");
  }

  robot.waitForRunExit();
 

  Aria::shutdown();
  exit(0);  
}
int __cdecl _tmain (int argc, char** argv)
{

	//------------ I N I C I O   M A I N    D E L   P R O G R A M A   D E L    R O B O T-----------//

	  //inicializaion de variables
	  Aria::init();
	  ArArgumentParser parser(&argc, argv);
	  parser.loadDefaultArguments();
	  ArSimpleConnector simpleConnector(&parser);
	  ArRobot robot;
	  ArSonarDevice sonar;
	  ArAnalogGyro gyro(&robot);
	  robot.addRangeDevice(&sonar);
	  ActionGos go(500, 350);	  
	  robot.addAction(&go, 48);
	  ActionTurns turn(400, 110);
	  robot.addAction(&turn, 49);
	  ActionTurns turn2(400, 110);
	  robot.addAction(&turn2, 49);

	  // presionar tecla escape para salir del programa
	  ArKeyHandler keyHandler;
	  Aria::setKeyHandler(&keyHandler);
	  robot.attachKeyHandler(&keyHandler);
	  printf("Presionar ESC para salir\n");

	  // uso de sonares para evitar colisiones con las paredes u 
	  // obstaculos grandes, mayores a 8cm de alto
	  ArActionLimiterForwards limiterAction("limitador velocidad cerca", 300, 600, 250);
	  ArActionLimiterForwards limiterFarAction("limitador velocidad lejos", 300, 1100, 400);
	  ArActionLimiterTableSensor tableLimiterAction;
	  robot.addAction(&tableLimiterAction, 100);
	  robot.addAction(&limiterAction, 95);
	  robot.addAction(&limiterFarAction, 90);


	  // Inicializon la funcion de goto
	  ArActionGoto gotoPoseAction("goto");
	  robot.addAction(&gotoPoseAction, 50);
	  
	  // Finaliza el goto si es que no hace nada
	  ArActionStop stopAction("stop");
	  robot.addAction(&stopAction, 40);

	  // Parser del CLI
	  if (!Aria::parseArgs() || !parser.checkHelpAndWarnUnparsed())
	  {    
		Aria::logOptions();
		exit(1);
	  }
	  
	  // Conexion del robot
	  if (!simpleConnector.connectRobot(&robot))
	  {
		printf("Could not connect to robot... exiting\n");
		Aria::exit(1);
	  }
	  robot.runAsync(true);

	  // enciende motores, apaga sonidos
	  robot.enableMotors();
	  robot.comInt(ArCommands::SOUNDTOG, 0);

	  // Imprimo algunos datos del robot como posicion velocidad y bateria
		robot.lock();
		ArLog::log(ArLog::Normal, "Posicion=(%.2f,%.2f,%.2f), Trans. Vel=%.2f, Bateria=%.2fV",
			robot.getX(), robot.getY(), robot.getTh(), robot.getVel(), robot.getBatteryVoltage());
		robot.unlock();

	  const int duration = 100000; //msec
	  ArLog::log(ArLog::Normal, "Completados los puntos en %d segundos", duration/1000);

	  // ============================ INICIO CONFIG COM =================================//
	    CSerial serial;
		LONG    lLastError = ERROR_SUCCESS;

		// Trata de abrir el com seleccionado
		lLastError = serial.Open(_T("COM3"),0,0,false);
		if (lLastError != ERROR_SUCCESS)
			return ::ShowError(serial.GetLastError(), _T("Imposible abrir el COM"));

		// Inicia el puerto serial (9600,8N1)
		lLastError = serial.Setup(CSerial::EBaud9600,CSerial::EData8,CSerial::EParNone,CSerial::EStop1);
		if (lLastError != ERROR_SUCCESS)
			return ::ShowError(serial.GetLastError(), _T("Imposible setear la config del COM"));

		// Register only for the receive event
		lLastError = serial.SetMask(CSerial::EEventBreak |
									CSerial::EEventCTS   |
									CSerial::EEventDSR   |
									CSerial::EEventError |
									CSerial::EEventRing  |
									CSerial::EEventRLSD  |
									CSerial::EEventRecv);
		if (lLastError != ERROR_SUCCESS)
			return ::ShowError(serial.GetLastError(), _T("Unable to set COM-port event mask"));

		// Use 'non-blocking' reads, because we don't know how many bytes
		// will be received. This is normally the most convenient mode
		// (and also the default mode for reading data).
		lLastError = serial.SetupReadTimeouts(CSerial::EReadTimeoutNonblocking);
		if (lLastError != ERROR_SUCCESS)
			return ::ShowError(serial.GetLastError(), _T("Unable to set COM-port read timeout."));
		// ============================ FIN CONFIG COM =================================//

	  bool first = true;
	  int goalNum = 0;
	  int color = 3;
	  ArTime start;
	  start.setToNow();
	  while (Aria::getRunning()) 
	  {
		robot.lock();

		// inicia el primer punto 
		if (first || gotoPoseAction.haveAchievedGoal())
		{
		  first = false;
		  
		  goalNum++; //cambia de 0 a 1 el contador
		  printf("El contador esta en: --> %d <---\n",goalNum);
		  if (goalNum > 20)
			goalNum = 1;

		  //comienza la secuencia de puntos
		  if (goalNum == 1)
		  {
			gotoPoseAction.setGoal(ArPose(1150, 0));
			ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
			gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
			// Imprimo algunos datos del robot como posicion velocidad y bateria
			robot.lock();
			ArLog::log(ArLog::Normal, "Posicion=(%.2f,%.2f,%.2f), Trans. Vel=%.2f, Bateria=%.2fV",
				robot.getX(), robot.getY(), robot.getTh(), robot.getVel(), robot.getBatteryVoltage());
			robot.unlock();
			// Create the sound queue.
			ArSoundsQueue soundQueue;
			// Run the sound queue in a new thread
			soundQueue.runAsync();
			std::vector<const char*> filenames;
			filenames.push_back("sound-r2a.wav");
			soundQueue.play(filenames[0]);
		  }
		  else if (goalNum == 2)
		  {
			  printf("Gira 90 grados izquierda\n");
			  robot.unlock();
			  turn.myActivate = 1;
			  turn.myDirection = 1;
			  turn.activate();
			  ArUtil::sleep(1000);
			  turn.deactivate();
			  turn.myActivate = 0;
			  turn.myDirection = 0;
			  robot.lock();
		  }
		  else if (goalNum == 3)
		  {
			gotoPoseAction.setGoal(ArPose(1150, 2670));
			ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
			gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
			// Imprimo algunos datos del robot como posicion velocidad y bateria
			robot.lock();
			ArLog::log(ArLog::Normal, "Posicion=(%.2f,%.2f,%.2f), Trans. Vel=%.2f, Bateria=%.2fV",
				robot.getX(), robot.getY(), robot.getTh(), robot.getVel(), robot.getBatteryVoltage());
			robot.unlock();
		  }
		  else if (goalNum == 4)
		  {
			  printf("Gira 90 grados izquierda\n");
			  robot.unlock();
			  turn2.myActivate = 1;
			  turn2.myDirection = 1;
			  turn2.activate();
			  ArUtil::sleep(1000);
			  turn2.deactivate();
			  turn2.myActivate = 0;
			  turn2.myDirection = 0;
			  robot.lock();
		  }
		  else if (goalNum == 5)
		  {
			gotoPoseAction.setGoal(ArPose(650, 2670));
			ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
			gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
		  }
		  else if (goalNum == 6)
		  {
			  printf("Gira 90 grados izquierda\n");
			  robot.unlock();
			  turn2.myActivate = 1;
			  turn2.myDirection = 1;
			  turn2.activate();
			  ArUtil::sleep(1000);
			  turn2.deactivate();
			  turn2.myActivate = 0;
			  turn2.myDirection = 0;
			  robot.lock();
		  }
		  else if (goalNum == 7)
		  {
			gotoPoseAction.setGoal(ArPose(650, 0));
			ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
			gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
		  }
		  else if (goalNum == 8)
		  {
			gotoPoseAction.setGoal(ArPose(1800,1199));
			ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
			gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
		  }
		  else if (goalNum == 9)
		  {
			gotoPoseAction.setGoal(ArPose(2600, 1199));
			ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
			gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
		  }
		  else if (goalNum == 10)
		  {
			  if (color == 1)
			  {
				gotoPoseAction.setGoal(ArPose(2800, 850));
				ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
				gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
			  }
			  if (color == 2)
			  {
				gotoPoseAction.setGoal(ArPose(3500, 1199));
				ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
				gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY()); 
			  }
			  if (color == 3)
			  {
				gotoPoseAction.setGoal(ArPose(2800, 1550));
				ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
				gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
			  }
		  }
		  else if (goalNum == 11)
		  {
			  if (color == 1)
			  {
				gotoPoseAction.setGoal(ArPose(2800, 613));
				ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
				gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
			  }
			  if (color == 2)
			  {
				  printf("Gira 180 grados derecha\n");
				  robot.unlock();
				  turn2.myActivate = 1;
				  turn2.myDirection = 2;
				  turn2.activate();
				  ArUtil::sleep(2000);
				  turn2.deactivate();
				  turn2.myActivate = 0;
				  turn2.myDirection = 0;
				  robot.lock();
				  goalNum = 19;
			  }
			  if (color == 3)
			  {
				gotoPoseAction.setGoal(ArPose(2800, 1785));
				ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
				gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
			  }
		  }
		  else if (goalNum == 12)
		  {
			  if (color == 1)
			  {
				gotoPoseAction.setGoal(ArPose(3300, 413));
				ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
				gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
			  }
			  if (color == 3)
			  {
				gotoPoseAction.setGoal(ArPose(3300, 1985));
				ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
				gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
			  }
		  }
		  else if (goalNum == 13)
		  {
			  if (color == 1)
			  {
				gotoPoseAction.setGoal(ArPose(3500, 413));
				ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
				gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
			  }
			  if (color == 3)
			  {
				gotoPoseAction.setGoal(ArPose(3500, 1985));
				ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
				gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
			  }
		  }
		  else if (goalNum == 14)
		  {
			  robot.unlock();
			  //Valor para el while
			  bool fContinue = true;
				// <<<<<<------------- 1 Parte Secuencia: BAJA BRAZO ------------->>>>>> //
				lLastError = serial.Write("b");
				if (lLastError != ERROR_SUCCESS)
					return ::ShowError(serial.GetLastError(), _T("Unable to send data"));

				//-------------------------E S C U C H A   C O M ----------------------------//
				do
				{
					// Wait for an event
					lLastError = serial.WaitEvent();
					if (lLastError != ERROR_SUCCESS)
						return ::ShowError(serial.GetLastError(), _T("Unable to wait for a COM-port event."));

					// Save event
					const CSerial::EEvent eEvent = serial.GetEventType();

					// Handle break event
					if (eEvent & CSerial::EEventBreak)
					{
						printf("\n### BREAK received ###\n");
					}

					// Handle CTS event
					if (eEvent & CSerial::EEventCTS)
					{
						printf("\n### Clear to send %s ###\n", serial.GetCTS()?"on":"off");
					}

					// Handle DSR event
					if (eEvent & CSerial::EEventDSR)
					{
						printf("\n### Data set ready %s ###\n", serial.GetDSR()?"on":"off");
					}

					// Handle error event
					if (eEvent & CSerial::EEventError)
					{
						printf("\n### ERROR: ");
						switch (serial.GetError())
						{
						case CSerial::EErrorBreak:		printf("Break condition");			break;
						case CSerial::EErrorFrame:		printf("Framing error");			break;
						case CSerial::EErrorIOE:		printf("IO device error");			break;
						case CSerial::EErrorMode:		printf("Unsupported mode");			break;
						case CSerial::EErrorOverrun:	printf("Buffer overrun");			break;
						case CSerial::EErrorRxOver:		printf("Input buffer overflow");	break;
						case CSerial::EErrorParity:		printf("Input parity error");		break;
						case CSerial::EErrorTxFull:		printf("Output buffer full");		break;
						default:						printf("Unknown");					break;
						}
						printf(" ###\n");
					}

					// Handle ring event
					if (eEvent & CSerial::EEventRing)
					{
						printf("\n### RING ###\n");
					}

					// Handle RLSD/CD event
					if (eEvent & CSerial::EEventRLSD)
					{
						printf("\n### RLSD/CD %s ###\n", serial.GetRLSD()?"on":"off");
					}

					// Handle data receive event
					if (eEvent & CSerial::EEventRecv)
					{
						// Read data, until there is nothing left
						DWORD dwBytesRead = 0;
						char szBuffer[101];
						do
						{
							// Lee datos del Puerto COM
							lLastError = serial.Read(szBuffer,sizeof(szBuffer)-1,&dwBytesRead);
							if (lLastError != ERROR_SUCCESS)
								return ::ShowError(serial.GetLastError(), _T("Unable to read from COM-port."));

							if (dwBytesRead > 0)
							{
								//Preseteo color
								int color = 0;
								// Finaliza el dato, asi que sea una string valida
								szBuffer[dwBytesRead] = '\0';
								// Display the data
								printf("%s", szBuffer);

								// <<<<<<----------- 2 Parte Secuencia: CIERRA GRIPPER ----------->>>>>> //
								if (strchr(szBuffer,76))
								{
									lLastError = serial.Write("c");
									if (lLastError != ERROR_SUCCESS)
										return ::ShowError(serial.GetLastError(), _T("Unable to send data"));
								}
								
								// <<<<<<------------- 3 Parte Secuencia: SUBE BRAZO ------------->>>>>> //
								if (strchr(szBuffer,117))
								{
									lLastError = serial.Write("s");
									if (lLastError != ERROR_SUCCESS)
										return ::ShowError(serial.GetLastError(), _T("Unable to send data"));
								}

								// <<<<<<------------- 4 Parte Secuencia: COLOR ------------->>>>>> //
								if (strchr(szBuffer,72))
								{
									lLastError = serial.Write("C");
									if (lLastError != ERROR_SUCCESS)
										return ::ShowError(serial.GetLastError(), _T("Unable to send data"));
								}

								// <<<<<<---------- 5.1 Parte Secuencia: COLOR ROJO---------->>>>>> //
								if (strchr(szBuffer,82))
								{
									color = 1;
									//salir del bucle
									fContinue = false;
								}

								// <<<<<<---------- 5.2 Parte Secuencia: COLOR AZUL ---------->>>>>> //
								if (strchr(szBuffer,66))
								{
									color = 2;
									//salir del bucle
									fContinue = false;
								}

								// <<<<<<---------- 5.3 Parte Secuencia: COLOR VERDE ---------->>>>>> //
								if (strchr(szBuffer,71))
								{
									color = 3;
									//salir del bucle
									fContinue = false;
								}
							}
						}
						while (dwBytesRead == sizeof(szBuffer)-1);
					}
				}
				while (fContinue);
				// Close the port again
				serial.Close();
				robot.lock();
		  }
		  else if (goalNum == 15)
		  {
			  printf("Gira 180 grados derecha\n");
			  robot.unlock();
			  turn2.myActivate = 1;
			  turn2.myDirection = 2;
			  turn2.activate();
			  ArUtil::sleep(2000);
			  turn2.deactivate();
			  turn2.myActivate = 0;
			  turn2.myDirection = 0;
			  robot.lock();
		  }
		  else if (goalNum == 16)
		  {
			  if (color == 1)
			  {
				gotoPoseAction.setGoal(ArPose(3300, 413));
				ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
				gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
			  }
			  if (color == 3)
			  {
				gotoPoseAction.setGoal(ArPose(3300, 1985));
				ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
				gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
			  }
		  }
		  else if (goalNum == 17)
		  {
			  if (color == 1)
			  {
				gotoPoseAction.setGoal(ArPose(2800, 603));
				ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
				gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
			  }
			  if (color == 3)
			  {
				gotoPoseAction.setGoal(ArPose(2800, 1795));
				ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
				gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
			  }
		  }
		  else if (goalNum == 18)
		  {
			  if (color == 1)
			  {
				gotoPoseAction.setGoal(ArPose(2800, 860));
				ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
				gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
			  }
			  if (color == 3)
			  {
				gotoPoseAction.setGoal(ArPose(2800, 1540));
				ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
				gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
			  }
		  }
		  else if (goalNum == 19)
		  {
			gotoPoseAction.setGoal(ArPose(2600, 1199));
			ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
			gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
		  }
		  else if (goalNum == 20)
		  {
			gotoPoseAction.setGoal(ArPose(1800, 1199));
			ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
			gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
		  }
		}

		if(start.mSecSince() >= duration) {
		  ArLog::log(ArLog::Normal, "No puede llegar al punto, y la aplicacion saldra en %d", duration/1000);
		  gotoPoseAction.cancelGoal();
		  robot.unlock();
		  ArUtil::sleep(3000);
		  break;
		}
	    
		robot.unlock();
		ArUtil::sleep(10);
	  }

	  // Robot desconectado al terminal el sleep
	  Aria::shutdown();

	//------------ F I N   M A I N    D E L   P R O G R A M A   D E L    R O B O T-----------//
    
    return 0;
}
int _tmain(int argc, char** argv)
{
    //-------------- M A I N    D E L   P R O G R A M A   D E L    R O B O T------------//
    //----------------------------------------------------------------------------------//

    //inicializaion de variables
    Aria::init();
    ArArgumentParser parser(&argc, argv);
    parser.loadDefaultArguments();
    ArSimpleConnector simpleConnector(&parser);
    ArRobot robot;
    ArSonarDevice sonar;
    ArAnalogGyro gyro(&robot);
    robot.addRangeDevice(&sonar);
    ActionTurns turn(400, 55);
    robot.addAction(&turn, 49);
    ActionTurns turn2(400, 55);
    robot.addAction(&turn2, 49);
    turn.deactivate();
    turn2.deactivate();

    // presionar tecla escape para salir del programa
    ArKeyHandler keyHandler;
    Aria::setKeyHandler(&keyHandler);
    robot.attachKeyHandler(&keyHandler);
    printf("Presionar ESC para salir\n");

    // uso de sonares para evitar colisiones con las paredes u
    // obstaculos grandes, mayores a 8cm de alto
    ArActionLimiterForwards limiterAction("limitador velocidad cerca", 300, 600, 250);
    ArActionLimiterForwards limiterFarAction("limitador velocidad lejos", 300, 1100, 400);
    ArActionLimiterTableSensor tableLimiterAction;
    robot.addAction(&tableLimiterAction, 100);
    robot.addAction(&limiterAction, 95);
    robot.addAction(&limiterFarAction, 90);


    // Inicializon la funcion de goto
    ArActionGoto gotoPoseAction("goto");
    robot.addAction(&gotoPoseAction, 50);

    // Finaliza el goto si es que no hace nada
    ArActionStop stopAction("stop");
    robot.addAction(&stopAction, 40);

    // Parser del CLI
    if (!Aria::parseArgs() || !parser.checkHelpAndWarnUnparsed())
    {
        Aria::logOptions();
        exit(1);
    }

    // Conexion del robot
    if (!simpleConnector.connectRobot(&robot))
    {
        printf("Could not connect to robot... exiting\n");
        Aria::exit(1);
    }
    robot.runAsync(true);

    // enciende motores, apaga sonidos
    robot.enableMotors();
    robot.comInt(ArCommands::SOUNDTOG, 0);

    // Imprimo algunos datos del robot como posicion velocidad y bateria
    robot.lock();
    ArLog::log(ArLog::Normal, "Posicion=(%.2f,%.2f,%.2f), Trans. Vel=%.2f, Bateria=%.2fV",
               robot.getX(), robot.getY(), robot.getTh(), robot.getVel(), robot.getBatteryVoltage());
    robot.unlock();

    const int duration = 100000; //msec
    ArLog::log(ArLog::Normal, "Completados los puntos en %d segundos", duration/1000);

    bool first = true;
    int goalNum = 0;
    int color = 3;
    ArTime start;
    start.setToNow();
    while (Aria::getRunning())
    {
        robot.lock();

        // inicia el primer punto
        if (first || gotoPoseAction.haveAchievedGoal())
        {
            first = false;

            goalNum++; //cambia de 0 a 1 el contador
            printf("El contador esta en: --> %d <---\n",goalNum);
            if (goalNum > 20)
                goalNum = 1;

            //comienza la secuencia de puntos
            if (goalNum == 1)
            {
                gotoPoseAction.setGoal(ArPose(1150, 0));
                ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                           gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
                // Imprimo algunos datos del robot como posicion velocidad y bateria
                robot.lock();
                ArLog::log(ArLog::Normal, "Posicion=(%.2f,%.2f,%.2f), Trans. Vel=%.2f, Bateria=%.2fV",
                           robot.getX(), robot.getY(), robot.getTh(), robot.getVel(), robot.getBatteryVoltage());
                robot.unlock();
            }
            else if (goalNum == 2)
            {
                printf("Gira 90 grados izquierda\n");
                robot.unlock();
                turn.myActivate = 1;
                turn.myDirection = 1;
                turn.activate();
                ArUtil::sleep(1000);
                turn.deactivate();
                turn.myActivate = 0;
                turn.myDirection = 0;
                robot.lock();
            }
            else if (goalNum == 3)
            {
                gotoPoseAction.setGoal(ArPose(1150, 2670));
                ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                           gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
                // Imprimo algunos datos del robot como posicion velocidad y bateria
                robot.lock();
                ArLog::log(ArLog::Normal, "Posicion=(%.2f,%.2f,%.2f), Trans. Vel=%.2f, Bateria=%.2fV",
                           robot.getX(), robot.getY(), robot.getTh(), robot.getVel(), robot.getBatteryVoltage());
                robot.unlock();
            }
            else if (goalNum == 4)
            {
                printf("Gira 90 grados izquierda\n");
                robot.unlock();
                turn2.myActivate = 1;
                turn2.myDirection = 1;
                turn2.activate();
                ArUtil::sleep(1000);
                turn2.deactivate();
                turn2.myActivate = 0;
                turn2.myDirection = 0;
                robot.lock();
            }
            else if (goalNum == 5)
            {
                gotoPoseAction.setGoal(ArPose(650, 2670));
                ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                           gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
            }
            else if (goalNum == 6)
            {
                printf("Gira 90 grados izquierda\n");
                robot.unlock();
                turn2.myActivate = 1;
                turn2.myDirection = 1;
                turn2.activate();
                ArUtil::sleep(1000);
                turn2.deactivate();
                turn2.myActivate = 0;
                turn2.myDirection = 0;
                robot.lock();
            }
            else if (goalNum == 7)
            {
                gotoPoseAction.setGoal(ArPose(650, 0));
                ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                           gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
            }
            else if (goalNum == 8)
            {
                gotoPoseAction.setGoal(ArPose(1800,1199));
                ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                           gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
            }
            else if (goalNum == 9)
            {
                gotoPoseAction.setGoal(ArPose(2600, 1199));
                ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                           gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
            }
            else if (goalNum == 10)
            {
                if (color == 1)
                {
                    gotoPoseAction.setGoal(ArPose(2800, 850));
                    ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                               gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
                }
                if (color == 2)
                {
                    gotoPoseAction.setGoal(ArPose(3500, 1199));
                    ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                               gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
                }
                if (color == 3)
                {
                    gotoPoseAction.setGoal(ArPose(2800, 1550));
                    ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                               gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
                }
            }
            else if (goalNum == 11)
            {
                if (color == 1)
                {
                    gotoPoseAction.setGoal(ArPose(2800, 613));
                    ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                               gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
                }
                if (color == 2)
                {
                    printf("Gira 180 grados derecha\n");
                    robot.unlock();
                    turn2.myActivate = 1;
                    turn2.myDirection = 2;
                    turn2.activate();
                    ArUtil::sleep(2000);
                    turn2.deactivate();
                    turn2.myActivate = 0;
                    turn2.myDirection = 0;
                    robot.lock();
                    goalNum = 19;
                }
                if (color == 3)
                {
                    gotoPoseAction.setGoal(ArPose(2800, 1785));
                    ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                               gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
                }
            }
            else if (goalNum == 12)
            {
                if (color == 1)
                {
                    gotoPoseAction.setGoal(ArPose(3300, 413));
                    ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                               gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
                }
                if (color == 3)
                {
                    gotoPoseAction.setGoal(ArPose(3300, 1985));
                    ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                               gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
                }
            }
            else if (goalNum == 13)
            {
                if (color == 1)
                {
                    gotoPoseAction.setGoal(ArPose(3500, 413));
                    ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                               gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
                }
                if (color == 3)
                {
                    gotoPoseAction.setGoal(ArPose(3500, 1985));
                    ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                               gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
                }
            }
            else if (goalNum == 14)
            {
                //secuencia de drop de la figura
            }
            else if (goalNum == 15)
            {
                printf("Gira 180 grados derecha\n");
                robot.unlock();
                turn2.myActivate = 1;
                turn2.myDirection = 2;
                turn2.activate();
                ArUtil::sleep(2000);
                turn2.deactivate();
                turn2.myActivate = 0;
                turn2.myDirection = 0;
                robot.lock();
            }
            else if (goalNum == 16)
            {
                if (color == 1)
                {
                    gotoPoseAction.setGoal(ArPose(3300, 413));
                    ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                               gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
                }
                if (color == 3)
                {
                    gotoPoseAction.setGoal(ArPose(3300, 1985));
                    ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                               gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
                }
            }
            else if (goalNum == 17)
            {
                if (color == 1)
                {
                    gotoPoseAction.setGoal(ArPose(2800, 603));
                    ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                               gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
                }
                if (color == 3)
                {
                    gotoPoseAction.setGoal(ArPose(2800, 1795));
                    ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                               gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
                }
            }
            else if (goalNum == 18)
            {
                if (color == 1)
                {
                    gotoPoseAction.setGoal(ArPose(2800, 860));
                    ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                               gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
                }
                if (color == 3)
                {
                    gotoPoseAction.setGoal(ArPose(2800, 1540));
                    ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                               gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
                }
            }
            else if (goalNum == 19)
            {
                gotoPoseAction.setGoal(ArPose(2600, 1199));
                ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                           gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
            }
            else if (goalNum == 20)
            {
                gotoPoseAction.setGoal(ArPose(1800, 1199));
                ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f",
                           gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
            }
        }

        if(start.mSecSince() >= duration) {
            ArLog::log(ArLog::Normal, "No puede llegar al punto, y la aplicacion saldra en %d", duration/1000);
            gotoPoseAction.cancelGoal();
            robot.unlock();
            ArUtil::sleep(3000);
            break;
        }

        robot.unlock();
        ArUtil::sleep(10);
    }

    // Robot desconectado al terminal el sleep
    Aria::shutdown();

//----------------------------------------------------------------------------------//

    return 0;
}
Пример #7
0
int main(int argc, char **argv)
{
  Aria::init();
  ArRobot robot;
  ArArgumentParser parser(&argc, argv);
  ArSimpleConnector simpleConnector(&parser);

  // The base server object, manages all connections to clients.
  ArServerBase server;

  // This object simplifies configuration and opening of the ArServerBase
  // object.
  ArServerSimpleOpener simpleOpener(&parser);

  // parse the command line. fail and print the help if the parsing fails
  // or if the help was requested with -help
  parser.loadDefaultArguments();
  if (!simpleConnector.parseArgs() || !simpleOpener.parseArgs() || 
      !parser.checkHelpAndWarnUnparsed())
  {    
    simpleConnector.logOptions();
    simpleOpener.logOptions();
    exit(1);
  }

  // Use the ArSimpleOpener to open the server port
  if (!simpleOpener.open(&server))
  {
    ArLog::log(ArLog::Terse, "Error: Could not open server on port %d", simpleOpener.getPort());
    exit(1);
  }


  //
  // Create services attached to the base server:
  // 
  
  // Robot position etc.:
  ArServerInfoRobot serverInfoRobot(&server, &robot);

  // Robot control modes (only one mode can be active at once):
  ArServerModeStop modeStop(&server, &robot);    
  // old ArServerModeDrive modeDrive(&server, &robot); 
  ArServerModeRatioDrive modeRatioDrive(&server, &robot);
  ArServerModeWander modeWander(&server, &robot);
  modeStop.addAsDefaultMode();
  modeStop.activate();

  // This provides a simple way to add new commands.
  ArServerHandlerCommands commands(&server);

  // Add our custom command. ArServerHandlerCommands also has other methods
  // for adding commands taht take different kinds of arguments, or no
  // arguments.
  ArGlobalFunctor1<ArArgumentBuilder*> customCommandFunctor(&customCommandHandler);
  commands.addStringCommand("ExampleCustomCommand", "Example of a custom command. simpleServerExample will print out the text sent with the command.", &customCommandFunctor);
 
  // These objects provide various debugging and diagnostic custom commands:
  ArServerSimpleComUC uCCommands(&commands, &robot);  // Get information about the robot
  ArServerSimpleComMovementLogging loggingCommands(&commands, &robot);  // Control logging
  modeRatioDrive.addControlCommands(&commands);  // Drive mode diagnostics

  // This provides the client (e.g. MobileEyes) with a simple table of string values
  // (called an InfoGroup). An InfoGroup is kept globally by Aria.
  // The values in the table sent to clients are retrieved periodically by calling a 
  // functor.
  ArServerInfoStrings stringInfo(&server);
  Aria::getInfoGroup()->addAddStringCallback(stringInfo.getAddStringFunctor());

  // Here are some example entries in the InfoGroup:
  Aria::getInfoGroup()->addStringInt(
	  "Motor Packet Count", 10, 
	  new ArConstRetFunctorC<int, ArRobot>(&robot, 
					       &ArRobot::getMotorPacCount));

  //
  // Connect to the robot:
  // 
  
  if (!simpleConnector.connectRobot(&robot))
  {
    printf("Error: Could not connect to robot... exiting\n");
    Aria::shutdown();
    return 1;
  }


  robot.enableMotors();
  robot.runAsync(true);

  // The simple opener might have information to display right before starting 
  // the server thread:
  simpleOpener.checkAndLog();

  // now let the server base run in a new thread, accepting client connections.
  server.runAsync();

  ArLog::log(ArLog::Normal, "Server is now running... Press Ctrl-C to exit.");

  robot.waitForRunExit();
  Aria::shutdown();
  exit(0);  
}
Пример #8
0
int
main(int argc, char *argv[])
{
  // Initialize location of Aria, Arnl and their args.
  Aria::init();
  Arnl::init();

  // The robot object
  ArRobot robot;
#ifndef SONARNL
  // The laser object
  ArSick sick(181, 361);
#endif

  // Parse them command line arguments.
  ArArgumentParser parser(&argc, argv);

  // Set up our simpleConnector
  ArSimpleConnector simpleConnector(&parser);

  // Load default arguments for this computer
  parser.loadDefaultArguments();

  // Parse its arguments for the simple connector.
  simpleConnector.parseArgs();

  // sonar, must be added to the robot, for teleop and wander
  ArSonarDevice sonarDev;
  // add the sonar to the robot
  robot.addRangeDevice(&sonarDev);

  ArMap arMap;
#ifndef SONARNL
  // Initialize the localization
  ArLocalizationTask locTask(&robot, &sick, &arMap);
  // Make the path task
  ArPathPlanningTask pathTask(&robot, &sick, &sonarDev, &arMap);
#else
  // Initialize the localization
  ArSonarLocalizationTask locTask(&robot, &sonarDev, &arMap);
  // Make the path task
  ArPathPlanningTask pathTask(&robot, NULL, &sonarDev, &arMap);
#endif


  // Stop the robot as soon as localization fails.
  ArFunctor1C<ArPathPlanningTask, int>
  locaFailed(&pathTask, &ArPathPlanningTask::trackingFailed);
  locTask.addFailedLocalizationCB(&locaFailed);

  // Read in param files.
  Aria::getConfig()->useArgumentParser(&parser);
  if (!Aria::getConfig()->parseFile(Arnl::getTypicalParamFileName()))
  {
    printf("Trouble loading configuration file, exiting\n");
    exit(1);
  }
  // Warn about unknown params.
  if (!parser.checkHelpAndWarnUnparsed())
  {
    printf("\nUsage: %s -map mapfilename\n\n", argv[0]);
    simpleConnector.logOptions();
    exit(2);
  }

  // Our server
  ArServerBase server;

  // First open the server up
  if (!server.open(7272))
  {
    printf("Could not open server port\n");
    exit(1);
  }

  // Connect the robot
  if (!simpleConnector.connectRobot(&robot))
  {
    printf("Could not connect to robot... exiting\n");
    Aria::shutdown();
    return 1;
  }

  robot.com2Bytes(31, 14, 0);
  robot.com2Bytes(31, 15, 0);
  ArUtil::sleep(100);
  robot.com2Bytes(31, 14, 1);
  robot.com2Bytes(31, 15, 1);
  robot.enableMotors();
  robot.clearDirectMotion();

#ifndef SONARNL
  // Set up the laser before handing it to the laser mode
  simpleConnector.setupLaser(&sick);

  // Add the laser to the robot
  robot.addRangeDevice(&sick);
#endif

  // Start the robot thread.
  robot.runAsync(true);

#ifndef SONARNL
  // Start the laser thread.
  sick.runAsync();

  // Connect the laser
  if (!sick.blockingConnect())
  {
    printf("Couldn't connect to sick, exiting\n");
    Aria::shutdown();
    return 1;
  }
#endif

  ArUtil::sleep(300);

  // If you want to set the number of samples change the line below
  locTask.setNumSamples(2000);
  // Localize the robot to home
  if(locTask.localizeRobotAtHomeBlocking())
  {
    printf("Successfully localized at home.\n");
  }
  else
  {
    printf("WARNING: Unable to localize at home position!\n");
  }


  robot.lock();
  // attach stuff to the server
  ArServerInfoRobot serverInfoRobot(&server, &robot);
  ArServerInfoSensor serverInfoSensor(&server, &robot);
  ArServerInfoPath serverInfoPath(&server, &robot, &pathTask);
  ArServerInfoLocalization serverInfoLocalization(&server, &robot, &locTask);

#ifndef SONARNL
  // Set it up to handle maps.
  ArServerHandlerMap serverMap(&server, &arMap, ArServerHandlerMap::POINTS);
#else
  ArServerHandlerMap serverMap(&server, &arMap, ArServerHandlerMap::LINES);
#endif

  // Set up a service that allows the client to monitor the communication
  // between the robot and the client.
  //
  ArServerHandlerCommMonitor serverCommMonitor(&server);


  //ArServerModeGoto modeGoto(&server, &robot, &pathTask);
  //ArServerModeStop modeStop(&server, &robot);
  //ArServerModeDrive modeDrive(&server, &robot);

  SimpleTask simpleTask(&robot, &pathTask);

  robot.unlock();
  // Read in param files.
  Aria::getConfig()->parseFile(Arnl::getTypicalParamFileName());

  // Now let it spin off in its own thread
  server.run();
  exit(0);

}
Пример #9
0
int main(int argc, char **argv)
{
  bool done;
  double distToTravel = 3000;
  int spinTime = 0;

  // set up our simpleConnector
  ArSimpleConnector simpleConnector(&argc, argv);
  // set up a key handler so escape exits and attach to the robot
  ArKeyHandler keyHandler;

  Aria::init();

  robot = new ArRobot;

  printf("You can press the escape key to exit this program\n");

  // parse its arguments
  if (simpleConnector.parseArgs())
  {
    simpleConnector.logOptions();
    exit(1);
  }

  // if there are more arguments left then it means we didn't
  // understand an option
  /*
  if (argc > 1)
  {    
    simpleConnector.logOptions();
    keyHandler.restore();
    exit(1);
  }
  */

  ArGlobalFunctor exitCB(&hardExit);
  ArGlobalFunctor printerCB(&printer);

  keyHandler.addKeyHandler(ArKeyHandler::ESCAPE, &exitCB);
  robot->attachKeyHandler(&keyHandler);
  Aria::setKeyHandler(&keyHandler);



  // set up the robot for connecting
  if (!simpleConnector.connectRobot(robot))
  {
    printf("Could not connect to robot... exiting\n");
    Aria::shutdown();
    keyHandler.restore();
    return 1;
  }

  //robot->addUserTask("printer", 50, &printerCB);
  // run the robot, true here so that the run will exit if connection lost
  robot->runAsync(true);

#ifdef WIN32
  // wait until someone pushes the motor button to go
  printf("Press the motor button to start the robot moving\n");
  while (1)
  {
    robot->lock();
    if (!robot->isRunning())
      hardExit();
    if (robot->areMotorsEnabled())
    {
      robot->unlock();
      break;
    }
    robot->unlock();
    ArUtil::sleep(100);
  }
#endif
  ArAnalogGyro *gyro;

  if (argc == 1)
  {
    printf("Gyro\n");
    gyro = new ArAnalogGyro(robot);
  }
  printf("Waiting for inertial to stabilize for 5 seconds.\n");
  // wait a bit for the inertial to warm up
  ArUtil::sleep(5000);
  // basically from here on down the robot just cruises around a bit
  robot->lock();
  // enable the motors, disable amigobot sounds
  robot->comInt(ArCommands::SONAR, 0);
  robot->comInt(ArCommands::ENABLE, 1);
  robot->setMoveDoneDist(200);

  // move a couple meters
  printf("Driving out\n");
  robot->move(distToTravel);
  robot->setHeading(0);
  robot->unlock();
  do {
    ArUtil::sleep(100);
    robot->lock();
    //robot->setHeading(0);
    done = robot->isMoveDone(200);
    robot->unlock();
  } while (!done);

  if (spinTime != 0)
  {
    printf("Spinning a while\n");
    // rotate a few times
    robot->lock();
    robot->setRotVel(200);
    robot->unlock();
    ArUtil::sleep(spinTime * 1000);
  }

  printf("Pointing back\n");
  robot->lock();
  robot->setHeading(180);
  robot->unlock();
  do {
    ArUtil::sleep(100);
    robot->lock();
    //robot->setHeading(180);
    done = robot->isHeadingDone(5);
    robot->unlock();
  } while (!done);

  printf("Driving back\n");
  // move a couple meters
  robot->lock();
  robot->move(distToTravel);
  robot->setHeading(180);
  robot->unlock();
  do {
    ArUtil::sleep(100);
    robot->lock();
    //robot->setHeading(180);
    done = robot->isMoveDone(200);
    robot->unlock();
  } while (!done);

  printf("Pointing back in original direction.\n");
  robot->lock();
  robot->setHeading(0);
  robot->unlock();
  do {
    ArUtil::sleep(100);
    robot->lock();
    //robot->setHeading(0);
    done = robot->isHeadingDone(5);
    robot->unlock();
  } while (!done);


  robot->lock();
  printf("Final heading %.2f\n", robot->getTh());
  robot->disconnect();
  robot->unlock();
  // now exit
  Aria::shutdown();
  return 0;
}
Пример #10
0
int main(int argc, char **argv)
{
  double speed = 1000;
  double squareSide = 2000;

  // whether to use the sim for the laser or not, if you use the sim
  // for hte laser, you have to use the sim for the robot too
  // robot
  robot = new ArRobot;
  // the laser
  ArSick sick;
  // set up our simpleConnector
  ArSimpleConnector simpleConnector(&argc, argv);

  // set up a key handler so escape exits and attach to the robot
  ArKeyHandler keyHandler;
  robot->attachKeyHandler(&keyHandler);

  // parse its arguments
  if (simpleConnector.parseArgs())
  {
    simpleConnector.logOptions();
    keyHandler.restore();
    exit(1);
  }

  // if there are more arguments left then it means we didn't
  // understand an option
  /*
  if (argc > 1)
  {    
    simpleConnector.logOptions();
    keyHandler.restore();
    exit(1);
  }
  */

  // set a default filename
  //std::string filename = "c:\\log\\1scans.2d";
  std::string filename = "1scans.2d";
  // see if we want to use a different filename
  //if (argc > 1)
  //Lfilename = argv[1];
  printf("Logging to file %s\n", filename.c_str());
  // start the logger with good values
  
  //sick.configureShort(useSim, ArSick::BAUD38400, 	 ArSick::DEGREES180, ArSick::INCREMENT_HALF);
  ArSickLogger logger(robot, &sick, 300, 25, filename.c_str());
  
  // mandatory init
  Aria::init();

  // add it to the robot
  robot->addRangeDevice(&sick);

  //ArAnalogGyro gyro(robot);


  // set up the robot for connecting
  if (!simpleConnector.connectRobot(robot))
  {
    printf("Could not connect to robot->.. exiting\n");
    Aria::shutdown();
    return 1;
  }

  robot->setRotVelMax(300);
  robot->setRotAccel(300);
  robot->setRotDecel(300);

  robot->setAbsoluteMaxTransVel(2000);
  robot->setTransVelMax(2000);
  robot->setTransAccel(500);
  robot->setTransDecel(500);
  /*
  robot->comInt(82, 30); // rotkp
  robot->comInt(83, 200); // rotkv
  robot->comInt(84, 0); // rotki
  robot->comInt(85, 15); // transkp
  robot->comInt(86, 450); // transkv
  robot->comInt(87, 4); // transki
  */
  robot->comInt(82, 30); // rotkp
  robot->comInt(83, 200); // rotkv
  robot->comInt(84, 0); // rotki
  robot->comInt(85, 30); // transkp
  robot->comInt(86, 450); // transkv
  robot->comInt(87, 4); // transki
  // run the robot, true here so that the run will exit if connection lost
  robot->runAsync(true);



  // set up the laser before handing it to the laser mode
  simpleConnector.setupLaser(&sick);

  // now that we're connected to the robot, connect to the laser
  sick.runAsync();

 if (!sick.blockingConnect())
  {
    printf("Could not connect to SICK laser... exiting\n");
    robot->disconnect();
    Aria::shutdown();
    return 1;
  }

  robot->lock();
  robot->addUserTask("printer", 50, new ArGlobalFunctor(&printer));
  robot->unlock();

#ifdef WIN32
  // wait until someone pushes the motor button to go
  while (1)
  {
    robot->lock();
    if (!robot->isRunning())
      exit(0);
    if (robot->areMotorsEnabled())
    {
      robot->unlock();
      break;
    }
    robot->unlock();
    ArUtil::sleep(100);
  }
#endif

  // basically from here on down the robot just cruises around a bit

  printf("Starting moving\n");
  robot->lock();
  // enable the motors, disable amigobot sounds
  robot->comInt(ArCommands::ENABLE, 1);
  robot->setHeading(0);
  robot->setVel(1000);
  robot->unlock();

  ArUtil::sleep(speed / 500.0 * 1000.0);
  printf("Should be up to speed, moving on first side\n");
  ArUtil::sleep(squareSide / speed * 1000);
  printf("Turning to second side\n");
  robot->lock();
  robot->setHeading(90);
  robot->setVel(speed);
  robot->unlock();
  ArUtil::sleep(squareSide / speed * 1000);
  printf("Turning to third side\n");
  robot->lock();
  robot->setHeading(180);
  robot->setVel(speed);
  robot->unlock();
  ArUtil::sleep(squareSide / speed * 1000);
  printf("Turning to last side\n");
  robot->lock();
  robot->setHeading(-90);
  robot->setVel(speed);
  robot->unlock();
  ArUtil::sleep(squareSide / speed * 1000);
  printf("Pointing back original direction and stopping\n");
  robot->lock();
  robot->setHeading(0);
  robot->setVel(0);
  robot->unlock();
  ArUtil::sleep(300);

  printf("Stopped\n");
  sick.lockDevice();
  sick.disconnect();
  sick.unlockDevice();
  robot->lock();
  robot->disconnect();
  robot->unlock();

  // now exit
  Aria::shutdown();
  return 0;
}
Пример #11
0
/*!
 * Main function which initializes the localization tasks and pathplanning
 * tasks.
 *
 * @param argc No of command line args.
 * @param argv Array of command line args.
 *
 * @return 1 if successful.
 */
int
main(int argc, char *argv[])
{
  char* mapname;

  if(argc<2){
    printf("%s\n",USAGE);
    exit(1);
  }

  Aria::init();
  Arnl::init();

  // The robot object
  ArRobot robot;
#ifndef SONARNL
  // The laser object
  ArSick sick(181, 361);
#endif


  // Set up our simpleConnector
  ArSimpleConnector simpleConnector(&argc, argv);

  // Parse its arguments
  simpleConnector.parseArgs();

  // Parse them command line arguments.
  ArArgumentParser parser(&argc, argv);

  // Sonar, must be added to the robot, for teleop and wander
  ArSonarDevice sonarDev;
  // Add the sonar to the robot
  robot.addRangeDevice(&sonarDev);

  // Set up the robot for connecting
  if (!simpleConnector.connectRobot(&robot))
  {
    printf("Could not connect to robot... exiting\n");
    Aria::shutdown();
    return 1;
  }

  robot.enableMotors();
  robot.clearDirectMotion();

#ifndef SONARNL
  // Set up the laser before handing it to the laser mode
  simpleConnector.setupLaser(&sick);

  // Add the laser to the robot
  robot.addRangeDevice(&sick);
#endif

  // Start the robot thread.
  robot.runAsync(true);

#ifndef SONARNL
  // Start the laser thread.
  sick.runAsync();

  // Connect the laser
  if (!sick.blockingConnect())
  {
    printf("Couldn't connect to sick, exiting\n");
    Aria::shutdown();
    return 1;
  }
#endif

  //
  // Set up the big holder.
  //
#ifndef SONARNL
  advancedptr = new Advanced(&robot, &sick, &sonarDev);
#else
  advancedptr = new Advanced(&robot, NULL, &sonarDev);
#endif
  //
  // Set up the callbacks for localization task.
  //
  ArFunctor1C<Advanced, int>
  failed(advancedptr, &Advanced::trackingFailed);
  //
  // Set up the callbacks for pathplanning task.
  //
  ArFunctor1C<Advanced, ArPose>
  goal_done(advancedptr, &Advanced::goalDone);
  ArFunctor1C<Advanced, ArPose>
  goal_failed(advancedptr, &Advanced::goalFailed);

  // Read in config file. Do this before creating the localization
  // and path planning tasks, so we can override certain config
  // parameters such as the map file name when we do so.
  if (!Aria::getConfig()->parseFile(Arnl::getTypicalParamFileName()))
  {
    printf("Trouble loading configuration file, exiting\n");
    exit(1);
  }

  //
  // Get mapname and initialize localization task and pathplanning tasks.
  //
  if((mapname = parser.checkParameterArgument("-map"))){
    //
    // Start the localization thread. Should be done first.
    //
    if(!advancedptr->initializeLocalizationTask(mapname)){
      printf("Cannot start the localization task thread.\n");
      exit(1);
    }else{
      printf("Started the Localization Thread\n");
    }
    //
    // Get the Aria map from the localization task .
    // (Alternatively use a ArMap* made separately)
    //
    advancedptr->myMap = advancedptr->myLocaTask->getAriaMap();
    //
    // Set up the path plan structure.
    // Cannot precede localization task setup.
    //
    if(!advancedptr->initializePathPlanningTask()){
      printf("Cannot set up for path planning task thread.\n");
      exit(1);
    }else{
      printf("Started Path Planning Thread\n");
    }
    //
    // Functors to be used by the Arnl library if the threads
    // signal failure or success.
    //
    advancedptr->myLocaTask->addFailedLocalizationCB(&failed);
    advancedptr->myPathPlanningTask->addGoalDoneCB(&goal_done);
    advancedptr->myPathPlanningTask->addGoalFailedCB(&goal_failed);

  }else{
    printf(USAGE);
    exit(1);
  }

  //
  // Get user input.
  //
  interact();

}
int APIENTRY _tWinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR    lpCmdLine,
                     int       nCmdShow)
{
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);

  //-------------- M A I N    D E L   P R O G R A M A   D E L    R O B O T------------//
  //----------------------------------------------------------------------------------------------------------
	
  //inicializaion de variables
  Aria::init();
  ArArgumentParser parser(&argc, argv);
  parser.loadDefaultArguments();
  ArSimpleConnector simpleConnector(&parser);
  ArRobot robot;
  ArSonarDevice sonar;
  ArAnalogGyro gyro(&robot);
  robot.addRangeDevice(&sonar);

  // presionar tecla escape para salir del programa
  ArKeyHandler keyHandler;
  Aria::setKeyHandler(&keyHandler);
  robot.attachKeyHandler(&keyHandler);
  printf("You may press escape to exit\n");

  // uso de sonares para evitar colisiones con las paredes u 
  // obstaculos grandes, mayores a 8cm de alto
  ArActionLimiterForwards limiterAction("speed limiter near", 300, 600, 250);
  ArActionLimiterForwards limiterFarAction("speed limiter far", 300, 1100, 400);
  ArActionLimiterTableSensor tableLimiterAction;
  robot.addAction(&tableLimiterAction, 100);
  robot.addAction(&limiterAction, 95);
  robot.addAction(&limiterFarAction, 90);


  // Inicializon la funcion de goto
  ArActionGoto gotoPoseAction("goto");
  robot.addAction(&gotoPoseAction, 50);
  
  // Finaliza el goto si es que no hace nada
  ArActionStop stopAction("stop");
  robot.addAction(&stopAction, 40);

  // Parser del CLI
  if (!Aria::parseArgs() || !parser.checkHelpAndWarnUnparsed())
  {    
    Aria::logOptions();
    exit(1);
  }
  
  // Conexion del robot
  if (!simpleConnector.connectRobot(&robot))
  {
    printf("Could not connect to robot... exiting\n");
    Aria::exit(1);
  }
  robot.runAsync(true);

  // enciende motores, apaga sonidos
  robot.enableMotors();
  robot.comInt(ArCommands::SOUNDTOG, 0);

  const int duration = 100000; //msec
  ArLog::log(ArLog::Normal, "Completados los puntos en %d segundos", duration/1000);

  bool first = true;
  int horiz = 1800;
  int vert = 380;
  int goalNum = 0;
  ArTime start;
  start.setToNow();
  while (Aria::getRunning()) 
  {
    robot.lock();
    // inicia el primer punto 
    if (first || gotoPoseAction.haveAchievedGoal())
    {
      first = false;
	  
      goalNum++; //cambia de 0 a 1 el contador
      if (goalNum > 7)
        goalNum = 1;

	  //comienza la secuencia de puntos
      if (goalNum == 1)
        gotoPoseAction.setGoal(ArPose(horiz, vert*0));
      else if (goalNum == 2)
        gotoPoseAction.setGoal(ArPose(0, vert*1));
      else if (goalNum == 3)
        gotoPoseAction.setGoa l(ArPose(horiz, vert*2)+5);
      else if (goalNum == 4)
        gotoPoseAction.setGoal(ArPose(0, vert*3));
	  else if (goalNum == 5)
        gotoPoseAction.setGoal(ArPose(horiz, vert*4+5));
	  else if (goalNum == 6)
        gotoPoseAction.setGoal(ArPose(0, vert*5));
	  else if (goalNum == 7)
        gotoPoseAction.setGoal(ArPose(0, vert*0));

      ArLog::log(ArLog::Normal, "Siguiente punto en %.0f %.0f", 
		    gotoPoseAction.getGoal().getX(), gotoPoseAction.getGoal().getY());
    }

    if(start.mSecSince() >= duration) {
      ArLog::log(ArLog::Normal, "%d seconds have elapsed. Cancelling current goal, waiting 3 seconds, and exiting.", duration/1000);
      gotoPoseAction.cancelGoal();
      robot.unlock();
      ArUtil::sleep(3000);
      break;
    }
    
    robot.unlock();
    ArUtil::sleep(100);
  }

  // Robot desconectado al terminal el sleep
  Aria::shutdown();
  return 0;

//----------------------------------------------------------------------------------------------------------

 	// TODO: Place code here.
	MSG msg;
	HACCEL hAccelTable;

	// Initialize global strings
	LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
	LoadString(hInstance, IDC_VENTANAROBOT, szWindowClass, MAX_LOADSTRING);
	MyRegisterClass(hInstance);

	// Perform application initialization:
	if (!InitInstance (hInstance, nCmdShow))
	{
		return FALSE;
	}

	hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_VENTANAROBOT));

	// Main message loop:
	while (GetMessage(&msg, NULL, 0, 0))
	{
		if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	return (int) msg.wParam;
}