Exemplo n.º 1
0
int _tmain(int argc, _TCHAR* argv[])
{
	/**
	 * Get all the arguments
	 * First is the filename of the executable
	 * Second should be the encrypted message file
	 * Third is the keyfile
	 * Fourth is the destination.
	 * ArgParser will do the job
	 */
	ArgParser* argparser = NULL;

	list<string> arg_list;

	for (int i = 1; i < argc; ++i)
	{
		arg_list.push_back(string(argv[i]));
	}

	argparser = new ArgParser(argc, arg_list);

	if (argparser->get_Valid_Arguments() < 3)
	{
		cout << "What2HTML" << " by <*****@*****.**>" << endl
			<< "Converts WhatsApp messages to HTML text" << endl << endl
			<< "Usage:" << endl
			<< argv[0] << " --encrypted-file=<sourcefile> --key-file=<keyfile> --output-file=<outfile>";
		return EXIT_ARGUMENT_ERROR;
	}
	return EXIT_SUCCESS;
}
Exemplo n.º 2
0
TEST( ArgParserTest, DashIsAnArg )
{
  ArgParser parser;
  const char* args[] = { "test", "-" };
  parser.Parse( 2, args );

  ASSERT_EQ( 1ul, parser.Arguments().size() );
  ASSERT_EQ( "-", parser.Arguments()[0] );
}
Exemplo n.º 3
0
/**
* <summary>
* Main Program Entry Point.
* </summary>
*/
int main(int argc, const char** argv) 
{
	int retval = 0;
	WriteHeader();

	//Add all the arguments.
	s_args.AddMapEntries( s_argmap);
	s_s1.RegisterArgs( "s1", s_args);
	s_s2.RegisterArgs( "s2", s_args);

	//Parse the arguments.
	retval = s_args.Parse( argc, argv);
	if( retval > 0)
	{
		int addr = (int) s_args.GetLong( "address");
		try {
			addr = s_cfgDevice.Attach(addr);
			printf("Attached to ASR-2300 at address = %d\n", addr);

		} catch (std::runtime_error& re) {
			printf("Error:  %s0\n", re.what());
			return -1;
		}

		// Dump the device information
		DumpDeviceInformation();

		//Initialize the stream loggers.
		retval = s_s1.Init( s_args, &s_cfgDevice);
		if( retval == 0)
			retval = s_s2.Init( s_args, &s_cfgDevice);
	
		//Receive the data and store to disk.
		if( retval == 0)
		{
			s_s1.DisplayConfiguration();
			s_s2.DisplayConfiguration();

			s_cfgDevice.Dci0Transport().ClearReceiveQueue();

			retval = ReceiveData((size_t) (s_args.GetDouble("duration")*1000.0));
		}

		s_s1.Terminate();
		s_s2.Terminate();
		s_cfgDevice.Detach();
	}
	else //Arguments were not right.
	{
		PrintUsage();
	}
	return retval;
}
Exemplo n.º 4
0
int main(int argc, char* argv[])
{
  try {
    SignalHandler::SetupHandlers();
    ArgParser argparser = ArgParser(argc, argv);
    Envelope *env = argparser.GetEnvelope();
    Client client = Client(env);
    client.SendMails();
    return 0;
  } catch (char const* err) {
    std::cerr << err << std::endl;
    return 1;
  }
}
Exemplo n.º 5
0
TEST( ArgParserTest, LongArgsTest )
{
  ArgParser parser;
  parser.AddOption( 'h', "hello" );
  parser.AddOption( 'g', "goodbye" );

  const char* args[] = { "test", "--hello", "--goodbye", "foo" };
  parser.Parse( 4, args );

  EXPECT_TRUE( parser.HasOption( 'h' ) );
  EXPECT_TRUE( parser.HasOption( "hello" ) );

  EXPECT_TRUE( parser.HasOption( 'g' ) );
  EXPECT_TRUE( parser.HasOption( "goodbye" ) );

  ASSERT_EQ( 1ul, parser.Arguments().size() );
  ASSERT_EQ( "foo", parser.Arguments()[0] );
}
Exemplo n.º 6
0
RCType
startTraceGen(int argc, char *argv[])
{
	RCType rc = RC_OK;
	Path *dir = NULL;

	if (RC_OK == help(argc, argv)) {
		return RC_OK;
	}

	J9TDFOptions options;
	TraceGen tracegen;
	ArgParser argParser;

	rc = argParser.parseOptions(argc, argv, &options);
	if (RC_OK != rc) {
		FileUtils::printError("Failed to parse command line options\n");
		goto failed;
	}

	if (options.force) {
		printf("tracegen -force option is enabled. All files will be regenerated.\n");
	}

	dir = options.rootDirectory;
	while (NULL != dir) {
		/* Recursively visit all directories under dirName, processing TDF files */
		if (RC_OK != FileUtils::visitDirectory(&options, dir->path, TDF_FILE_EXT, &tracegen, TraceGen::generateCallBack)) {
			FileUtils::printError("Failed to generate trace files\n");
			goto failed;
		}
		dir = dir->next;
	}
	tracegen.tearDown();
	argParser.freeOptions(&options);
	return rc;
failed:
	tracegen.tearDown();
	argParser.freeOptions(&options);
	return RC_FAILED;
}
Exemplo n.º 7
0
//	extracts a vector<expr> that represents a core input extracted with Utils::read_core_file method
//	return 0 if successful (core in resulting clause), or a positive integer if unsuccessful (with empty resultingClause). 
void CoreParser::extractInitialCore(expr& ast, ArgParser parser, vector<expr>& resultingCore) {
	vector<string> initialCore;
	read_core_file(parser.getInputFile(), initialCore);
	vector<expr> core;
	unsigned i;
	for (i = 0; i < initialCore.size(); ++i) {
		int index = -1;
		try {
			index = std::stoi(initialCore[i].substr(initialCore[i].find('c', 0)+1, initialCore[i].size() - 1)); // line should be of the form "C<num>" where C is a char and <num> is an integer between 0 and the number of clauses in the ast
		}
		catch (std::invalid_argument& e) {
			resultingCore.clear();
			throw PropsitionalCoreParserException((string(__func__) + ": ERROR in parsing clause named " + initialCore[i] + "at line " + std::to_string(i) + " in core file,  clause not named in the form 'C<num>' (for a given number num)").c_str(),3);
		}
		if (0 > index || ast.num_args() <= index) {
			resultingCore.clear();
			throw PropsitionalCoreParserException((string(__func__) + ": ERROR index "+ std::to_string(index) + ", at line " + std::to_string(i) + " in core file is out of bounds of formula.").c_str(),4);
		}
		resultingCore.push_back(ast.arg(index));
	}
}
  virtual void run() {
    {
      ArgParser parser;
      Arg arg1(parser, false, "arg1", "<value>");
      Arg required2(parser, true, "required2", "<value>");
      const char* args[] = {
        "myExecutable",
        "-arg1", "myValue1",
        "-required2", "myRequired2",
        0
      };
      assertTrue(parser.parse(sizeof(args) / sizeof(char*) - 1, args));
      assertEqual("myValue1", arg1.value);
      assertEqual("myRequired2", required2.value);
    }

    {
      ArgParser parser;
      Arg arg1(parser, false, "arg1", "<value>");
      Arg required2(parser, true, "required2", "<value>");
      const char* args[] = {
        "myExecutable",
        "-arg1", "myValue1",
        "-required2",
        0
      };
      assertFalse(parser.parse(sizeof(args) / sizeof(char*) - 1, args));
    }

    {
      ArgParser parser;
      Arg arg1(parser, false, "arg1", "<value>");
      Arg required2(parser, true, "required2", "<value>");
      const char* args[] = {
        "myExecutable",
        "-arg1", "myValue1",
        0
      };
      assertFalse(parser.parse(sizeof(args) / sizeof(char*) - 1, args));
    }
  }
Exemplo n.º 9
0
int xcrun(int argc, char **argv, Target &target) {
  if (getenv("xcrun_log"))
    showCommand = true;

  constexpr const char *ENVVARS[] = {
    "DEVELOPER_DIR", "TOOLCHAINS", "xcrun_verbose"
  };

  for (const char *evar : ENVVARS) {
    if (getenv(evar)) {
      warn << "xcrun: ignoring environment variable "
           << "'" << evar << "'" << warn.endl();
    }
  }

  if (char *SDK = getenv("SDKROOT")) {
    unsetenv("OSXCROSS_SDKROOT");
    char *argv[1] = { SDK };
    sdk(target, argv);
  }

  auto dummy = [](Target&, char**) { return 0; };

  ArgParser<int (*)(Target&, char**), 19> argParser = {{
    {"h", help},
    {"help", help},
    {"version", version},
    {"v", dummy},
    {"verbose", dummy},
    {"k", dummy},
    {"kill-cache", dummy},
    {"n", dummy},
    {"no-cache", dummy},
    {"sdk", sdk, 1},
    {"toolchain", dummy, 1},
    {"l", log },
    {"log", log},
    {"f", find, 1},
    {"find", find, 1},
    {"r", run, 1},
    {"run", run, 1},
    {"show-sdk-path", showSDKPath},
    {"show-sdk-version", showSDKVersion}
  }};

  int retVal = 1;

  for (int i = 1; i < argc; ++i) {
    auto b = argParser.parseArg(argc, argv, i);

    if (!b) {
      if (argv[i][0] == '-') {
        err << "xcrun: unknown argument: '" << argv[i] << "'" << err.endl();
        retVal = 2;
        break;
      }

      run(target, &argv[i]);
    }

    retVal = b->fun(target, &argv[i + 1]);

    if (retVal != 0)
      break;

    i += b->numArgs;
  }

  return retVal;
}
Exemplo n.º 10
0
/**
* <summary>
* Prints usage of this program, on command line parsing error.
* </summary>
*/
static void PrintUsage() {
	printf( "\nUsage for DualRxToFile:\n\n"
		"  DualRxToFile <s1.filename> <s2.filename> [[<var>=<value>] ...]\n\n");

	s_args.WriteDescriptions();
}
Exemplo n.º 11
0
TEST( ArgParserTest, ThrowsOnUnknownLongArgs )
{
  ArgParser parser;
  const char* args[] = { "test", "--hello" };
  EXPECT_THROW( parser.Parse( 2, args ), Error );
}
Exemplo n.º 12
0
Arquivo: main.cpp Projeto: Ape/xboxdrv
int main(int argc, char** argv)
{
  enum {
    OPTION_HELP,
    OPTION_DEVICE
  };

  gtk_init(&argc, &argv);

  ArgParser argp;
  argp
    .add_usage("[OPTION]...")
    .add_text("Virtual Keyboard")
    .add_newline()
 
    .add_option(OPTION_HELP,   'h', "help", "", "display this help and exit")
    .add_option(OPTION_DEVICE, 'd', "device", "DEVICE", "read events from device");

  ArgParser::ParsedOptions parsed = argp.parse_args(argc, argv);
  std::string device;
  for(ArgParser::ParsedOptions::const_iterator i = parsed.begin(); i != parsed.end(); ++i)
  {
    const ArgParser::ParsedOption& opt = *i;

    switch (i->key)
    {
      case OPTION_HELP:
        argp.print_help(std::cout);
        exit(EXIT_SUCCESS);
        break;

      case OPTION_DEVICE:
        device = opt.argument;
        break;
    }
  }

  StatusIcon status_icon;
  KeyboardDescriptionPtr keyboard_desc = KeyboardDescription::create_us_layout(); 
  VirtualKeyboard virtual_keyboard(keyboard_desc);

  if (!device.empty())
  {
    UInput uinput(false);
    KeyboardDispatcher dispatcher(virtual_keyboard, uinput);
    KeyboardController controller(virtual_keyboard, uinput, device);
    uinput.finish();

    virtual_keyboard.show();
    gtk_main();
  }
  else
  { 
    {
      std::cout << "--device DEVICE option not given, starting in test mode" << std::endl;
    
      // non-interactive test mode
      virtual_keyboard.show();
      gtk_main();
    }

    return EXIT_SUCCESS;
  }
}
Exemplo n.º 13
0
Arquivo: jnn.c Projeto: 10crimes/code
void main(int argc,String *argv) {
  mcheck();
  randomise();

  a=ArgParser(argc,argv);

 
  nnname=a.argafter("-nn","nn name","current.net");
  tsname=a.argafter("-ts","trainset name","current.pat");
  eacq=a.intafter("-eqcq","Edge Angle Cancelling histogram quantisation",16);
  eacrad=a.intafter("-eacrad","Default radius for eac",6);
  glq=a.intafter("-glq","greylevel quantisation",32);
  glhistrad=a.intafter("-glvr","Default radius for gl variance",3);
  windres=a.intafter("-wskip","pixel skip for window segmentation",5);
  botres=a.intafter("-br","bottom res for neighbour segmenter (botres*2^n=topres)",2);
  topres=a.intafter("-tr","top res",32);
  notext=a.floatafter("-nt","not text if < than",-4.5);
  istext=a.floatafter("-it","is text if > than",-2.0);
  show=a.argexists("-show","show results of measures");
  usenumpostrainexs=a.intafter("-nptes","number of positive training examples to output",50);
  usenumnegtrainexs=a.intafter("-nntes","number of positive training examples to output",50);
  scale=a.floatafter("-s","scale",0.5);
  morphrad=a.intafter("-mr","radius for morphology",3);
  twooutnodes=true; // a.argexists("-to","two output nodes");
  minarea=a.intafter("-ms","minimum size of kept region",200);
//  ghistscale=a.floatafter("-ghs","scale for hist stability",0.5);

  a.opts.add("task = trainset | newnn | trainnn | scan | test");
  String task=a.arg("task");
 
  if (Seq(task,"trainset")) {
      a.opts.add("trainset task = new | image | finish");
      String task2=a.arg("trainset task");

      if (Seq(task2,"new")) {
        tsname=a.argor(tsname);
        a.done();
        makenewtrainingset();

      } else if (Seq(task2,"image")) {
        iname=a.arg("image file");
        a.done();
        trainimage();

      } else if(Seq(task2,"finish")) {
        a.done();
        finishtrainingset();

      } else {
        a.done();
        error("Please choose a task for the training set");

      }

  } else if (Seq(task,"newnn")) {
      a.opts.add("nn type = hopfield | banana");
      String type=a.arg("nn type");
      a.done();
      makenewnn(type);

  } else if (Seq(task,"trainnn")) {
      a.done();
      trainnetwork();
    
  } else if (Seq(task,"scan")) {
      iname=a.arg("image file");
      a.done();
      scanimage();
    
  } else if (Seq(task,"test")) {
      iname=a.arg("image file");
      a.done();
      testimage();

  } else {
      a.done();
      error("Please choose a task.");

  }

  printf("jnn : Finished.\n");
Exemplo n.º 14
0
int main(int argc, char **argv)
{
   using namespace std;  

   retVal_t returnvalue = rvOK;

   ArgParser AP;
   AP.AddFile(".mat"); /* sysmat */
   AP.AddFile(".rhs", false); /* rhsvec */
   AP.AddFile(".cfg"); /* params */
   AP.AddFile(".sol", false); /* solvec */
   AP.AddOption("-c"); /* cmpmat */
   AP.AddFlag("-h");
	
   if (!AP.Parse(argc, argv))
   {
      cout << "try " << argv[0] << " -h for help" << endl;
      return(rvArgumentError);
   }

   if (AP.FlagSet("-h"))
   {
      printUsageMessage(argv[0]);
      return(returnvalue);
   }

   if (!AP.FileSet(".mat") || !AP.FileSet(".rhs"))
   {
      cout << "system matrix file (.mat) and rhs vector file (.rhs) have to be specified !\n"
           << "try " << argv[0] << " -h for help" << endl;
      return(rvArgumentError);
   }
   

   cout << "Welcome to mattest4c!\n";

   /* Reading system matrix */
   /* ===================== */

   qqqMCSR<qqqComplex> A;
   qqqSolverParameters parms;
   qqqError error;

   cout << "Reading System Matrix (file \"" << AP.FileStr(".mat") << "\") ... " << flush;
   if (!A.readMatrix(AP.FileStr(".mat")))
   {
      cout << "not ok!" << endl;
      return(rvIOError);
   }
   else cout << "ok!\n";

   qqqIndex dimension = A.dimension();

   if (dimension < 1)
   {
      cout << "Error: dimension of system matrix is smaller than 1!" << endl;
      return(rvFormatError);
   }

   cout <<"Backwriting to \"" << (AP.OptionSet("-c") ? AP.OptionStr("-c") : "compare.mat") << "\"... " << flush;
   A.writeMatrix(AP.OptionSet("-c") ? AP.OptionStr("-c") : "compare.mat", true, true);
   cout << "ok!\n";

   /* Reading parameter file */
   /* ====================== */

   if (AP.FileSet(".cfg"))
   {
      cout << "Reading solver parameter file (file \"" << AP.FileStr(".cfg") << "\") ... " << flush;
      if (!parms.readParameters(AP.FileStr(".cfg")))
      {
         cout << "not ok (using default)!\n";
         parms.setDefaultSolverParameters();
      }
      else cout << "ok!\n";
   }   

   /* Allocating memory */
   /* ================= */

   cout << "Allocating memory (dimension = " << qqqIndexToLong(dimension) << ") ... " << flush;

   qqqComplex *x = new qqqComplex[parms.nrhs * dimension];
   qqqComplex *b = new qqqComplex[parms.nrhs * dimension];

#if 1
   qqqComplex **mB;
   qqqComplex **mX;
   if (parms.nrhs > 1)
   {
      mB = new qqqComplex*[parms.nrhs];
      mX = new qqqComplex*[parms.nrhs];

      for (qqqIndex ccirhs = 0; ccirhs < parms.nrhs; ccirhs++)
      {
	 mB[ccirhs] = &b[ccirhs * dimension];
	 mX[ccirhs] = &x[ccirhs * dimension];
      }
   }
   else
   {
      mB = &b; 
      mX = &x;
   }
#endif

   if ((x == NULL) || (b == NULL))
   {
      cout << "not ok [insufficient memory]!\n";
      returnvalue = rvAllocErr;
   }
   else cout << "ok!\n";

   /* Reading right hand side vector(s) */
   /* ================================= */

   //char filename[40];
   string filename;

   if (returnvalue == rvOK)
   {
      cout << "Reading " << parms.nrhs << " right hand side vector(s) (file series \"" << AP.FileStr(".rhs") << "\") ..." << endl; 
      returnvalue = rvIOError;

      for (qqqIndex ccirhs = 0; ccirhs < parms.nrhs; ccirhs++)
      {
         stringstream sbuf;
         sbuf << AP.FileStr(".rhs") << ccirhs << ends;
         sbuf >> filename;
	 qqqIndex readRetval = qqqReadVector(&b[ccirhs * dimension], dimension, filename.c_str());
	 if (readRetval == -1)
	    cout << "   " << filename << ": not ok [file not found]!\n";
	 else if (readRetval == -2)
	    cout << "   " << filename << ": not ok [header mismatch]!\n";
	 else if (readRetval == -3)
	    cout << "   " << filename << ": not ok [dimension mismatch]!\n";
	 else if (readRetval == -4)
            cout << "   " << filename << ": not ok [end of file error]!\n";
	 else if (readRetval != dimension)
            cout << "   " << filename << ": not ok [format error: row " << readRetval << "]!\n";
	 else
	 {
            cout << "   " << filename << ": ok!\n";
	    returnvalue = rvOK;     
	 }

	 if (returnvalue != rvOK)
	    break;
      }
   }
Exemplo n.º 15
0
int _tmain(int argc, _TCHAR* argv[])
{
	VectorReader myVectorReader;
	VectorRecord_t currentVector;
	ArgParser myArgParser;

	unsigned long seconds_counter = 0;
	unsigned long steps_counter = 0;
	bool update_vector = false;
	bool update_PID_control = false;
	bool last_iteration = false;
	
	float plantState;
	float processF;
	uint16_t processValue;
	float setPointF;
	uint16_t setPoint; 
	uint16_t setPoint_old = 0;
	float effect = 0;
	
	float k_norm = 0.446f;
	float offset_norm = 48.144f;

	float tempSetting;							// Temperature setting
	bool reg_enabled;								// Heater ON/OFF
	uint8_t pid_mode;
	
	char *input_fname;
	char *output_dir;
	char *tmp_arg_str;
	int simulation_mode;

	char tmp_buf_char[100];

	//--------------------------------------------//
	// Command line arguments parsing

	myArgParser.Parse(argc, (char **)argv);
	 //myArgParser.PrintOptions();
	 //std::cin.get();
	 //return 0;

	if (!(input_fname = myArgParser.GetOptionValue("-input")))
	{
		std::cout << "Expected test vector file (-input <file>)" << std::endl;
		std::cin.get();
		return 0;
	}
	
	if (!(output_dir = myArgParser.GetOptionValue("-outdir")))
	{
		std::cout << "Expected output directory (-outdir <directory>)" << std::endl;
		std::cin.get();
		return 0;
	}

	if (!(tmp_arg_str = myArgParser.GetOptionValue("-mode")))
	{
		std::cout << "Expected simulation mode (-mode <PLANT_STEP / NORMAL>)" << std::endl;
		std::cin.get();
		return 0;
	}
	simulation_mode = (strcmp(tmp_arg_str, "PLANT_STEP") == 0) ? SIM_PLANT_STEP_RESPONSE : SIM_NORMAL;

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



	//-----------------------------//
	// Reading test vector file
	if (myVectorReader.ReadVectorFile(input_fname) == false)
	{
		std::cout << "Cannot read test vector file. Press any key to exit." << std::endl;
		std::cin.get();
		return 0;
	}

	std::cout << "Test vector file OK. Starting simulation." << std::endl;


	//-----------------------------//
	// Initializing simulation
	
	if (!CreateDirectory(output_dir,NULL))
	{
		if (GetLastError() != ERROR_ALREADY_EXISTS)
		{
			std::cout << "Cannot create output log directory" << std::endl;
			std::cin.get();
			return 0;
		}
	}

	// Open LOG files
	FILE *f_state_float;
	FILE *f_state_int;
	FILE *f_setting;
	FILE *f_p_term;
	FILE *f_d_term;
	FILE *f_i_term;
	FILE *f_pid_output;

	// Create log data files:

	// Plant state float
	sprintf_s(tmp_buf_char, 100, "%s%s", output_dir, "col_0f.txt");
	fopen_s( &f_state_float, tmp_buf_char, "w" ); 
	// Plant state integer
	sprintf_s(tmp_buf_char, 100, "%s%s", output_dir, "col_0.txt");
	fopen_s( &f_state_int, tmp_buf_char, "w" ); 
	// Set value
	sprintf_s(tmp_buf_char, 100, "%s%s", output_dir, "setting.txt");
	fopen_s( &f_setting, tmp_buf_char, "w" ); 
	// P-term of PID controller
	sprintf_s(tmp_buf_char, 100, "%s%s", output_dir, "col_5.txt");
	fopen_s( &f_p_term, tmp_buf_char, "w" ); 
	// D-term of PID controller
	sprintf_s(tmp_buf_char, 100, "%s%s", output_dir, "col_6.txt");
	fopen_s( &f_d_term, tmp_buf_char, "w" ); 
	// I-term of PID controller
	sprintf_s(tmp_buf_char, 100, "%s%s", output_dir, "col_7.txt");
	fopen_s( &f_i_term, tmp_buf_char, "w" ); 
	// Output of PID controller
	sprintf_s(tmp_buf_char, 100, "%s%s", output_dir, "col_8.txt");
	fopen_s( &f_pid_output, tmp_buf_char, "w" ); 
	

	// Set ambient temperature and plant internal state
	if (!myVectorReader.StartConditions.AmbientValid)
		myVectorReader.StartConditions.Ambient = 25;
	if (!myVectorReader.StartConditions.StateValid)
		myVectorReader.StartConditions.SystemState = 25;
	initPlant((float)myVectorReader.StartConditions.Ambient, (float)myVectorReader.StartConditions.SystemState); 
	processPlant(0);

	// Initialize PID controller 
	setPIDIntegratorLimit(0);
	
	// Initial simulator state
	reg_enabled = false;		// heater OFF
	tempSetting = 25.0f;		// Temperature default setting
	myVectorReader.GetNextVector(&currentVector);
	
	//int32_t aaa;
	//aaa = INT32_MAX;
	//printf("%d",aaa);
	//std::cin.get();

	//-----------------------------//
	// Simulate

	while(true)
	{
		// Process time counters
		update_vector = false;
		update_PID_control = false;
		if (steps_counter % STEPS_PER_SECOND == 0)
		{
			if (seconds_counter == currentVector.TimeStamp)
			{
				update_vector = true;
			}
			if (seconds_counter % PID_CALL_INTERVAL == 0)
			{
				update_PID_control = true;
			}
			seconds_counter++;
		}
		steps_counter++;

		// Update setting using data from test vector file
		if (update_vector)
		{
			if (last_iteration)
			{
				printf("%10lu sec. Simulation finished.\n", currentVector.TimeStamp);
				break;
			}
			
			reg_enabled = currentVector.ProcessEnabled;
			if (reg_enabled)
			{
				tempSetting = (float)currentVector.ForceValue;		
				setPIDIntegratorLimit((int)tempSetting);
			}
			
			if (reg_enabled)
				printf("%10lu sec. New setting = %.2f\n", currentVector.TimeStamp, tempSetting);
			else
				printf("%10lu sec. New setting = %s\n", currentVector.TimeStamp, "OFF");
			
			last_iteration = !myVectorReader.GetNextVector(&currentVector);
			//std::cin.get();
		}


		// Process plant with TIMESTEP interval
		processPlant(effect);	
		
		// Process regulator 
		if (simulation_mode == SIM_PLANT_STEP_RESPONSE)
		{
				if (reg_enabled)
					effect = 100;
				else
					effect = 0;
				dbg_PID_output = (int16_t)effect;
		}
		else
		{
				if (update_PID_control)
				{	
					// Calculate process value
					plantState = (float)getPlantState();					
					processF = (plantState + offset_norm) / k_norm;	
					processF *= 4;
					//processF /= 2;
					processValue = (uint16_t)processF;
			
					// Calculate setpoint
					setPointF = (tempSetting + offset_norm) / k_norm;
					setPointF *= 4;
					//setPointF /= 2;
					setPoint = (uint16_t)setPointF;	
			
					// PID
					pid_mode = 0;
					if (reg_enabled)
						pid_mode |= PID_ENABLED;
					effect = processPID(setPoint, processValue,pid_mode);
				}
		}
		

		// LOG
		fprintf(f_state_float, "%f\r", getPlantState());
		fprintf(f_state_int, "%u\r", (uint16_t)getPlantState());		
		fprintf(f_setting, "%d\r", (int)tempSetting);
		fprintf(f_p_term, "%d\r", dbg_PID_p_term);
		fprintf(f_d_term, "%d\r", dbg_PID_d_term);
		fprintf(f_i_term, "%d\r", dbg_PID_i_term);
		fprintf(f_pid_output, "%d\r", dbg_PID_output);

	}

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


	
	fclose(f_state_float);
	fclose(f_state_int);
	fclose(f_setting);
	fclose(f_p_term);
	fclose(f_d_term);
	fclose(f_i_term);
	fclose(f_pid_output);
	
	std::cout << "Done. Press enter to exit." << std::endl;
	std::cin.get();

	return 0;
}
Exemplo n.º 16
0
/**main
 * gets the command line arguments, set parameters accordingly and triggers the data acquisition to generate CSV files.
 * Input data are contained in a RINEX observation or navigation file containing header and epoch data.
 * The output is a CSV (Comma Separated Values) text data file. This type of files can be used to import data to some available
 * application (like MS Excel).
 * A detailed definition of the RINEX format can be found in the document "RINEX: The Receiver Independent Exchange
 * Format Version 2.10" from Werner Gurtner; Astronomical Institute; University of Berne. An updated document exists
 * also for Version 3.01.
 *
 *@param argc the number of arguments passed from the command line
 *@param argv the array of arguments passed from the command line
 *@return  the exit status according to the following values and meaning::
 *		- (0) no errors have been detected
 *		- (1) an error has been detected in arguments
 *		- (2) error when opening the input file
 *		- (3) error when reading, setting or printing header data
 *		- (4) error in data filtering parameters
 *		- (5) there were format errors in epoch data or no epoch data exist
 *		- (6) error when creating output file
 *		- (7) inconsistent data in RINEX VERSION header record
 */
int main(int argc, char* argv[]) {
	int anInt;		//a general purpose int variable
	string aStr;	//a general purpose string variable
	string fileName;
	double aDouble;	//a general purpose double variable
	/**The main process sequence follows:*/
	/// 1- Defines and sets the error logger object
	Logger log("LogFile.txt", string(), string(argv[0]) + MYVER + string(" START"));
	/// 2- Setups the valid options in the command line. They will be used by the argument/option parser
	TOT = parser.addOption("-t", "--totime=TOT", "TOT", "Select epochs before the given date and time (comma separated yyyy,mm,dd,hh,mm,sec", "");
	SELSAT = parser.addOption("-s", "--selsat", "SELSAT", "Select system-satellite from input (comma separated list of sys-prn, like G01,G02)", "");
	SELOBS2 = parser.addOption("-p", "--selobs2", "SELOBS2", "Select system-observable (ver.2.10 notation) from input (comma separated list, like C1,L1,L2)", "");
	SELOBS3 = parser.addOption("-o", "--selobs", "SELOBS3", "Select system-observable (ver.3.01 notation) from input (comma separated list, like GC1C,GL1C)", "");
	LOGLEVEL = parser.addOption("-l", "--llevel", "LOGLEVEL", "Maximum level to log (SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST)", "INFO");
	HELP = parser.addOption("-h", "--help", "HELP", "Show usage data and stops", false);
	FROMT = parser.addOption("-f", "--fromtime=FROMT", "FROMT", "Select epochs from the given date and time (comma separated yyyy,mm,dd,hh,mm,sec", "");
	/// 3- Setups the default values for operators in the command line
	INRINEX = parser.addOperator("RINEX.DAT");
	/// 4- Parses arguments in the command line extracting options and operators
	try {
		parser.parseArgs(argc, argv);
	}  catch (string error) {
		parser.usage("Argument error: " + error, CMDLINE);
		log.severe(error);
		return 1;
	}
	log.info(parser.showOptValues());
	log.info(parser.showOpeValues());
	if (parser.getBoolOpt(HELP)) {
		//help info has been requested
		parser.usage("Parses and read the given observation RINEX file generating a CSV ot TXT file with the requested characteristics", CMDLINE);
		return 0;
	}
	/// 5- Sets logging level stated in option. Default level is INFO
	log.setLevel(parser.getStrOpt(LOGLEVEL));
	/// 7 - Set 1st and last epoch time tags (if selected from / to epochs time) 
	TimeIntervalParams timeInterval;
	int week, year, month, day, hour, minute;
	double tow, second;
	aStr = parser.getStrOpt(FROMT);
	if (!aStr.empty()) {
		if (sscanf(aStr.c_str(), "%d,%d,%d,%d,%d,%lf", &year, &month, &day, &hour, &minute, &second) != 6) {
			log.severe("Cannot state 'from time' for the time interval");
			return 1;
		}
		setWeekTow (year, month, day, hour, minute, second, week, tow);
		timeInterval.fromTimeTag = getSecsGPSEphe(week, tow);
		timeInterval.fromTime = true;
	} else timeInterval.fromTime = false;
	aStr = parser.getStrOpt(TOT);
	if (!aStr.empty()) {
		if (sscanf(aStr.c_str(), "%d,%d,%d,%d,%d,%lf", &year, &month, &day, &hour, &minute, &second) != 6) {
			log.severe("Cannot state 'to time' for the time interval");
			return 1;
		}
		setWeekTow (year, month, day, hour, minute, second, week, tow);
		timeInterval.toTimeTag = getSecsGPSEphe(week, tow);
		timeInterval.toTime = true;
	} else timeInterval.toTime = false;
	/// 7- Opens the RINEX input file passed as operator
	FILE* inFile;
	fileName = parser.getOperator(INRINEX);
	if ((inFile = fopen(fileName.c_str(), "r")) == NULL) {
		log.severe("Cannot open file " + fileName);
		return 2;
	}
	/// 8- Create a RINEX object and extract header data from the RINEX input file
	RinexData rinex(RinexData::VTBD, &log);
	char fileType = ' ';
	char sysId = ' ';
	try {
		rinex.readRinexHeader(inFile);
		if (!rinex.getHdLnData(RinexData::INFILEVER, aDouble, fileType, sysId)) {
			log.severe("This RINEX input file version cannot be processed");
			fclose(inFile);
			return 3;
		}
	}  catch (string error) {
		log.severe(error);
		fclose(inFile);
		return 3;
	}
	/// 9 - Set filtering parameters passed in options, if any
	//convert obsV2Tokens to V3 and append them to obsTokens
	vector<string> obsV2Tokens = getTokens(parser.getStrOpt(SELOBS2), ',');
	vector<string> obsTokens = getTokens(parser.getStrOpt(SELOBS3), ',');
	for (vector<string>::iterator it = obsV2Tokens.begin(); it != obsV2Tokens.end(); it++) {
		aStr = rinex.obsV2toV3((*it).substr(1));
		if (aStr.empty()) log.warning("Filtering data: ignored unknown V2 observable " + aStr);
		else obsTokens.push_back((*it).substr(0,1) + aStr);
	}
	//verify coherence of SELSAT w.r.t. fileType and system identifier
	vector<string> selsat = getTokens(parser.getStrOpt(SELSAT), ',');
	if (fileType == 'N' && sysId == 'M') {
		if (selsat.empty()) {
			log.severe("File is Navigation type 'M', and no sytem was selected.");
			return 4;
		} else {
			//state sysId as per the 1st satellite selected
			sysId = selsat[0].at(0);
		}
	}
	if (!rinex.setFilter(selsat, obsTokens))
		log.warning("Ignored inconsistent data filtering parameters for observation files.");
	/// 10 - Create output file for header data (suffix name _HDR.CSV), print them, and close output file
	FILE* outFile;
	while ((anInt = fileName.find('.')) != string::npos) fileName.replace(anInt, 1, "_"); 	//replace . by _ in fileName
	aStr = fileName + "_HDR.CSV";
	if ((outFile = fopen(aStr.c_str(), "w")) == NULL) {
		log.severe("Cannot create file " + aStr);
		return 6;
	}
	generateHeaderCSV(outFile, rinex, &log);
	fclose(outFile);
	rinex.clearHeaderData();
	/// 11 - Create output file for observation or navigation data
	switch (fileType) {
	case 'O':
		/// 11.1- If observation file, create output file (suffix name _OBS.CSV), and epoch by epoch read its data and print them. Close output file
		aStr = fileName + "_OBS.CSV";
		if ((outFile = fopen(aStr.c_str(), "w")) == NULL) {
			log.severe("Cannot create file " + aStr);
			return 6;
		}
		anInt = generateObsCSV(inFile, outFile, rinex, timeInterval, &log);
		fclose(outFile);
		break;
	case 'N':
		/// 11.2 - If navigation file, create output file (suffix name _xxxNAV.CSV), and epoch by epoch read its data and print them. Close output file
		switch (sysId) {
		case 'G':
			aStr = fileName + "_GPSNAV.CSV";
			if ((outFile = fopen(aStr.c_str(), "w")) == NULL) {
			log.severe("Cannot create file " + aStr);
			return 6;
			}
			anInt = generateGPSNavCSV(inFile, outFile, rinex, timeInterval, &log);
			fclose(outFile);
			break;
		case 'E':
			aStr = fileName + "_GALNAV.CSV";
			if ((outFile = fopen(aStr.c_str(), "w")) == NULL) {
				log.severe("Cannot create file " + aStr);
				return 6;
			}
			anInt = generateGalNavCSV(inFile, outFile, rinex, timeInterval, &log);
			fclose(outFile);
			break;
		case 'R':
			aStr = fileName + "_GLONAV.CSV";
			if ((outFile = fopen(aStr.c_str(), "w")) == NULL) {
				log.severe("Cannot create file " + aStr);
				return 6;
			}
			anInt = generateGloNavCSV(inFile, outFile, rinex, timeInterval, &log);
			fclose(outFile);
			break;
		case 'S':
			aStr = fileName + "_SBASNAV.CSV";
			if ((outFile = fopen(aStr.c_str(), "w")) == NULL) {
				log.severe("Cannot create file " + aStr);
				return 6;
			}
			anInt = generateSBASNavCSV(inFile, outFile, rinex, timeInterval, &log);
			fclose(outFile);
			break;
		default:	//should not happen
			log.severe("Unexpected system type for navigation file");
			return 7;
		}
		break;
	default:
			log.severe("Unexpected file type, different from Observation or Navigation");
			return 7;
	}
	fclose(inFile);
	return anInt>0? 0:5;
}
Exemplo n.º 17
0
void fun(ClientInfo *clientinfo,const char *b)
{
     
     printf("Server:ENTER PROCESS______________________________\n");
     string localfilename="../webpage"; 
     Request req(b);
     ResponseHeader httpheader;
     ArgParser parser;
     string affix;
     string arg;
     string filename;
     char param[500];
     
     


     if(req.method=="GET"||req.content!="")
     {
         if(req.method=="GET")
         cout<<"(IP: "<<clientinfo->ip<<")"<<"Browser:GET "<<req.uri_full<<endl;
         else if(req.content!="")
         cout<<"(IP: "<<clientinfo->ip<<")"<<"Browser:POST "<<req.content<<endl;
         //全请求 
         string fullfilename=req.uri_full;
         //请求文件 
         filename=req.uri_name;
         localfilename+="/";
         localfilename+=filename;
         //请求文件后缀 
         affix=req.uri_affix;  
         //请求参数 
         arg=req.uri_arg;
         strcpy(param,arg.c_str());
         //获得接口 
         
         if(req.content!="")
         {
           clientinfo->PostSpace=(char *)malloc(req.content.length()+3);
           if(clientinfo->PostSpace==0)
           cout<<endl<<"Server:PostSpace Allocate Error"<<endl;
           memset(clientinfo->PostSpace,0,req.content.length()+3);
           strcpy(clientinfo->PostSpace,req.content.c_str());
         }
         else
           clientinfo->PostSpace=0;
           
           
         parser.parse(arg.c_str());
         string src=parser.get("srcpool");
         string stobesent;
         BYTE* btobesent;
         Resource *presorce;
         int ret;
         WebInterface inter;
         if(src!="")
         {
             cout<<"Server:Load Src"<<endl;
  
             presorce=SerSourcePool[fullfilename];
             if(presorce==0)
             {
             cout<<"Server:Load SRC ERR"<<endl;
             return;
             }
             cout<<"Server:Load Over"<<endl;
              //getchar();
             if(presorce->obsolete==1||clientinfo->PostSpace)
             {
               inter.getEntry(localfilename);
               cout<<"Server:Src Obosolete"<<endl;
               //  Webmain  Webmain  Webmain  Webmain  Webmain  Webmain  Webmain  Webmain  Webmain  Webmain  Webmain  Webmain  
               ret=inter.webmain(clientinfo,param,filename);
               if(ret==-1)
               {
               cout<<"Server:Load DLL Err"<<endl;
               return ; 
               }
             }
              
             
             if(presorce->Type=="TEXT")
             {
               stobesent=SerSourcePool[fullfilename]->Text; 
               httpheader.settype(presorce->MimeType.c_str());
               httpheader.setsize(stobesent.length());
               httpheader.prepareheader();  
               //send   send   send   send   send   send   send   send   send   send   send   send   send   send   send   send   
               send(clientinfo->clientsocket,httpheader.content.c_str(),httpheader.content.size(),0);
               send(clientinfo->clientsocket,stobesent.c_str(),stobesent.length(),0);
               clearClientInfo(clientinfo);
               presorce->obsolete=1;
               return ;
               
             }
             if(presorce->Type=="BIN")
             {
           //     printf("SERIMAGEsize:%d,Ptr:%d\n",SerSourcePool[fullfilename]->BinL,SerSourcePool[fullfilename]->Bin);
                
                
                btobesent= SerSourcePool[fullfilename]->Bin;  
                httpheader.settype(presorce->MimeType.c_str()); 
                httpheader.setsize(presorce->BinL);     
                httpheader.prepareheader(); 
                //send   send   send   send   send   send   send   send   send   send   send   send   send   send   send   send 
                send(clientinfo->clientsocket,httpheader.content.c_str(),httpheader.content.size(),0);    
                send(clientinfo->clientsocket,(char *)btobesent,presorce->BinL,0);  
                clearClientInfo(clientinfo);
                return;       
                                      
             }

                    
                    
         }
         

         
         
         if(affix=="exe"||affix=="dll")
         {
           //  Webmain  Webmain  Webmain  Webmain  Webmain  Webmain  Webmain  Webmain  Webmain  Webmain  Webmain  Webmain  
           cout<<"Server:WebMain Entry"<<endl;
           inter.getEntry(localfilename);
           ret=inter.webmain(clientinfo,param,filename);
           cout<<"Server:WebMain Ret"<<endl;
           if(ret==-1)
           {
             cout<<"Server:Load DLL Err";
             return ; 
           }
           cout<<"Server:Extract Src From Dll"<<endl;
           for(map<string,Resource*>::iterator itr=clientinfo->SourcePool->begin();itr!=clientinfo->SourcePool->end();
               itr++)
           {
              SerSourcePool[itr->first]=itr->second; 
           }
           cout<<"Server:Extract Src Over"<<endl;
           
           httpheader.settype(clientinfo->MainSrc->MimeType.c_str());
           if(clientinfo->MainSrc->Type=="TEXT")
           httpheader.setsize(clientinfo->MainSrc->Text.length());
           else if(clientinfo->MainSrc->Type=="BIN")
           httpheader.setsize(clientinfo->MainSrc->BinL);
           httpheader.prepareheader();
           
           //send   send   send   send   send   send   send   send   send   send   send   send   send   send   send   send 
           send(clientinfo->clientsocket,httpheader.content.c_str(),httpheader.content.size(),0);
           if(clientinfo->MainSrc->Type=="TEXT")
           send(clientinfo->clientsocket,clientinfo->MainSrc->Text.c_str(),clientinfo->MainSrc->Text.length(),0);
           else if(clientinfo->MainSrc->Type=="BIN")
           send(clientinfo->clientsocket,(char *)clientinfo->MainSrc->Bin,clientinfo->MainSrc->BinL,0);
           clearClientInfo(clientinfo);
           return ;
          }
          
          else
          {
             
             BigFile file(localfilename.c_str());   
               
             httpheader.setfile(file,file.size);
             httpheader.prepareheader();
             send(clientinfo->clientsocket,httpheader.content.c_str(),httpheader.content.size(),0);
             double flag=file.sendfile(clientinfo->clientsocket);  
             return;
              
          }

         
          
     }

     
}