コード例 #1
0
ファイル: testargstr.c プロジェクト: argtable/argtable3
void test_argstr_basic_003(CuTest* tc) {
    struct arg_str* a = arg_str0(NULL, "hello,world", "STRVAL", "either --hello or --world or none");
    struct arg_str* b = arg_str0("bB", NULL, "STRVAL", "either -b or -B or none");
    struct arg_str* c = arg_str1("cC", NULL, "STRVAL", "either -c or -C");
    struct arg_str* d = arg_strn("dD", "delta", "STRVAL", 2, 4, "-d|-D|--delta 2..4 occurences");
    struct arg_end* end = arg_end(20);
    void* argtable[] = {a, b, c, d, end};
    int nerrors;

    char* argv[] = {"program", "-Cstring1", "--delta=string2", "--delta=string3", NULL};
    int argc = sizeof(argv) / sizeof(char*) - 1;

    CuAssertTrue(tc, arg_nullcheck(argtable) == 0);

    nerrors = arg_parse(argc, argv, argtable);
    if (nerrors > 0)
        arg_print_errors(stdout, end, argv[0]);

    CuAssertTrue(tc, nerrors == 0);
    CuAssertTrue(tc, a->count == 0);
    CuAssertTrue(tc, b->count == 0);
    CuAssertTrue(tc, c->count == 1);
    CuAssertStrEquals(tc, c->sval[0], "string1");
    CuAssertTrue(tc, d->count == 2);
    CuAssertStrEquals(tc, d->sval[0], "string2");
    CuAssertStrEquals(tc, d->sval[1], "string3");

    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
}
コード例 #2
0
ファイル: apputil.cpp プロジェクト: hach-que/AppTools
int main(int argc, char* argv[])
{
    // Setup.
    AppLib::Logging::setApplicationName(std::string("apputil"));
    struct arg_file *script = arg_file1(NULL, NULL, "script", "the path of the script to execute");
    struct arg_end *end = arg_end(20);
    void *argtable[] = { script, end };
    script->filename[0] = NULL;

    // Check to see if the argument definitions were allocated
    // correctly.
    if (arg_nullcheck(argtable))
    {
        AppLib::Logging::showErrorW("Insufficient memory.");
        return 1;
    }

    // Now parse the arguments.
    int nerrors = arg_parse(argc, argv, argtable);

    // Check to see if there were errors.
    if (nerrors > 0 && script->filename[0] == NULL)
    {
        printf("Usage: apputil");
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, "apputil");
        
        printf("AppUtil - The application scripting utility.\n\n");
        arg_print_glossary(stdout, argtable, "    %-25s %s\n");
        return 1;
    }

    // Execute.
    return runPython(script->filename[0], argc, argv);
}
コード例 #3
0
ファイル: tmpcache_host.c プロジェクト: ma-everett/tmpcache
int main (int argc, char **argv) {

  void *argtable[] = {
    help = arg_lit0("h","help","print this screen"),
    verbose = arg_lit0("v","verbose","tell me everything"),
    fsyslog = arg_lit0(NULL,"syslog","use syslog"),
    cachepath = arg_file1(NULL,NULL,"cachepath","directory or .cdb database file"),
    netaddress0 = arg_file1(NULL,NULL,"read_address","zmq read network address"),
    netaddress1 = arg_file1(NULL,NULL,"write_address","zmq write network address"),
    end = arg_end(20),
  };
  
  int32_t nerrors = arg_parse(argc,argv,argtable);
  
  if (help->count) {
    
    fprintf(stdout,"tmpcache %s - version 0\n",__FUNCTION__);
    arg_print_syntaxv(stdout,argtable,"\n\n");
    arg_print_glossary (stdout,argtable,"%-25s %s\n");
   
    goto finish;
  }

  if (verbose->count) {

    fprintf(stdout,"tmpcache host - version 0\n");
    int32_t major,minor,patch;
    zmq_version (&major,&minor,&patch);
    fprintf(stdout,"compiled with zmq support %d.%d.%d\n",major,minor,patch);

    goto finish;
  }

  if (nerrors) {
    
    arg_print_errors (stdout,end,"");
    arg_print_syntaxv(stdout,argtable,"\n\n");
    goto finish;
  }

 
  u_term = 0;
  signal (SIGINT,signalhandler);
  signal (SIGTERM,signalhandler);

  if (fsyslog->count)
    openlog (NULL,LOG_PID|LOG_NDELAY,LOG_USER);

  void *read (void *arg) {

    tc_readconfig_t *config = (tc_readconfig_t *)arg;

    if (fsyslog->count)
      syslog (LOG_INFO,"reading cache from %s @ %s",btocstr(config->cachepath),btocstr(config->address));
    
    tc_readfromcache (config);
    
    if (fsyslog->count)
      syslog (LOG_INFO,"closing cache %s @ %s for reading",btocstr(config->cachepath),btocstr(config->address));     
  }
コード例 #4
0
static int eth_cmd_control(int argc, char **argv)
{
    int nerrors = arg_parse(argc, argv, (void **)&eth_control_args);
    if (nerrors != 0) {
        arg_print_errors(stderr, eth_control_args.end, argv[0]);
        return 1;
    }

    if (!strncmp(eth_control_args.control->sval[0], "start", 5) && !started) {
        ESP_ERROR_CHECK(esp_eth_enable());
        started = true;
    }
    if (!strncmp(eth_control_args.control->sval[0], "stop", 4) && started) {
        ESP_ERROR_CHECK(esp_eth_disable());
        started = false;
    }
    if (!strncmp(eth_control_args.control->sval[0], "info", 4)) {
        uint8_t mac_addr[6];
        esp_eth_get_mac(mac_addr);
        printf("HW ADDR: " MACSTR "\r\n", MAC2STR(mac_addr));
        tcpip_adapter_get_ip_info(ESP_IF_ETH, &ip);
        printf("ETHIP: " IPSTR "\r\n", IP2STR(&ip.ip));
        printf("ETHMASK: " IPSTR "\r\n", IP2STR(&ip.netmask));
        printf("ETHGW: " IPSTR "\r\n", IP2STR(&ip.gw));
    }
    return 0;
}
コード例 #5
0
ファイル: argcustom.c プロジェクト: SebastianSchlag/KaHIP
int main(int argc, char **argv)
    {
    struct arg_xxx  *scalar  = arg_xxx1(NULL, NULL, "<scalar>",            0.0, 1.0, "<double> value in range [0.0, 1.0]");
    struct arg_xxx  *x       = arg_xxx0("x",  NULL, "<double>",           -1.0, 1.0, "x coeff in range [-1.0, 1.0]");
    struct arg_xxx  *y       = arg_xxxn("y",  NULL, "<double>", 0,argc+2,  0.5, 0.9, "y coeff in range [0.5, 0.9]");
    struct arg_lit  *help    = arg_lit0(NULL,"help",                                 "print this help and exit");
    struct arg_end  *end     = arg_end(20);
    void* argtable[] = {scalar,x,y,help,end};
    const char* progname = "argcustom";
    int nerrors;
    int exitcode=0;
    int i;

    /* verify the argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable) != 0)
        {
        /* NULL entries were detected, some allocations must have failed */
        printf("%s: insufficient memory\n",progname);
        exitcode=1;
        goto exit;
        }

    /* Parse the command line as defined by argtable[] */
    nerrors = arg_parse(argc,argv,argtable);

    /* special case: '--help' takes precedence over error reporting */
    if (help->count > 0)
        {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout,argtable,"\n");
        printf("This program demonstrates the use of the argtable2 library\n");
        printf("for parsing command line arguments.\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
        exitcode=0;
        goto exit;
        }

    /* If the parser returned any errors then display them and exit */
    if (nerrors > 0)
        {
        /* Display the error details contained in the arg_end struct.*/
        arg_print_errors(stdout,end,progname);
        printf("Try '%s --help' for more information.\n",progname);
        exitcode=1;
        goto exit;
        }

    /* only get here is command line arguments were parsed sucessfully */
    printf("scalar = %f\n", scalar->data[0]);
    if (x->count > 0)
        printf("x = %f\n", x->data[0]);
    for (i=0; i<y->count; i++)
        printf("y[%d] = %f\n", i, y->data[i]);

    exit:
    /* deallocate each non-null entry in argtable[] */
    arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0]));

    return exitcode;
    }
コード例 #6
0
ファイル: application.cpp プロジェクト: mlapshin/revisor
bool Application::initArgtable()
{
  const char* progname = "revisor";
  struct arg_str* l   = arg_str0("l", NULL, "<interface>",   "Interface to listen, default '127.0.0.1'");
  struct arg_int* p   = arg_int0("p", NULL, "<port number>", "Port to listen, default 8080");
  struct arg_lit* h   = arg_lit0("h", "help",                "This help message");
  struct arg_end* end = arg_end(20);
  void *argtable[]  = {l, p, h, end};

  int nerrors = arg_parse(argc, argv, argtable);

  // special case: '--help' takes precedence over error reporting
  if (h->count > 0) {
    printf("Usage: %s", progname);
    arg_print_syntax(stdout, argtable, "\n");
    arg_print_glossary(stdout, argtable, "  %-25s %s\n");
    return false;
  }

  if (nerrors > 0) {
    arg_print_errors(stdout, end, progname);
    return false;
  }

  if (l->count > 0) {
    listeningInterface = l->sval[0];
  }

  if (p->count > 0) {
    portNumber = *p->ival;
  }

  arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
  return true;
}
コード例 #7
0
ファイル: dslink.c プロジェクト: kaendfinger/sdk-dslink-c
static
int dslink_parse_opts(int argc,
                      char **argv,
                      DSLinkConfig *config) {
    int ret = 0;
    struct arg_lit *help;
    struct arg_str *broker, *log;
    struct arg_end *end;

    void *argTable[] = {
        help = arg_lit0("h", "help", "Displays this help menu"),
        broker = arg_str1("b", "broker", "url", "Sets the broker URL to connect to"),
        log = arg_str0("l", "log", "log type", "Sets the logging level"),
        end = arg_end(5)
    };

    if (arg_nullcheck(argTable) != 0) {
        return DSLINK_ALLOC_ERR;
    }

    int errs = arg_parse(argc, argv, argTable);

    if (help->count > 0) {
        printf("Usage: <opts>\n");
        arg_print_glossary(stdout, argTable, " %-25s %s\n");
        ret = 1;
        goto exit;
    }

    if (errs > 0) {
        dslink_print_help();
        arg_print_errors(stdout, end, ":");
        ret = 1;
        goto exit;
    }

    config->broker_url = broker->sval[0];

    if (log->count > 0) {
        char lvl[8];
        const char *src = log->sval[0];
        size_t len = strlen(src);
        if (len > sizeof(lvl)) {
            len = sizeof(lvl);
        }
        memcpy(lvl, src, len);
        if (dslink_log_set_lvl(lvl, len) != 0) {
            printf("Invalid log level: %s\n", lvl);
            dslink_print_help();
            ret = 1;
            goto exit;
        }
    }

exit:
    arg_freetable(argTable, sizeof(argTable) / sizeof(argTable[0]));
    return ret;
}
コード例 #8
0
ファイル: cmdl-args.c プロジェクト: pbtrung/cfeap
static int cargs_print_error(struct arg_end *end)
{
    int rc = -1;

    arg_print_errors(stdout, end, PROGRAM_NAME);
    printf("Try '%s --help' for more information.\n\n", PROGRAM_NAME);

    return rc;
}
コード例 #9
0
ファイル: callbacks.c プロジェクト: Debug-Orz/sploit-dev
int main(int argc, char **argv)
    {
    struct arg_int  *val = arg_intn(NULL,NULL,NULL,2,100,"must be an even number of non-zero integer values that sum to 100");
    struct arg_end  *end = arg_end(20);
    void* argtable[] = {val,end};
    const char* progname = "callbacks";
    int nerrors;
    int exitcode=0;
    int i;

    /* verify the argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable) != 0)
        {
        /* NULL entries were detected, some allocations must have failed */
        printf("%s: insufficient memory\n",progname);
        exitcode=1;
        goto exit;
        }

    /* replace the default arg_int parsing and error validation routines with our own custom routines */
    val->hdr.scanfn  = (arg_scanfn*)myscanfn;
    val->hdr.checkfn = (arg_checkfn*)mycheckfn;
    val->hdr.errorfn = (arg_errorfn*)myerrorfn;

    /* special case: no command line options induces brief help */
    if (argc==1)
        {
        printf("Usage: %s ", progname);
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"where: %s %s\n");
        exitcode=0;
        goto exit;
        }

    /* Parse the command line as defined by argtable[] */
    nerrors = arg_parse(argc,argv,argtable);

    /* If the parser returned any errors then display them and exit */
    if (nerrors > 0)
        {
        /* Display the error details contained in the arg_end struct.*/
        arg_print_errors(stdout,end,progname);
        exitcode=1;
        goto exit;
        }

    /* parsing was succesful, print the values obtained */
    for (i=0; i<val->count; i++)
        printf("val->ival[%d] = %d\n",i, val->ival[i]);

    exit:
    /* deallocate each non-null entry in argtable[] */
    arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0]));

    return exitcode;
    }
コード例 #10
0
ファイル: lpfw-pygui.c プロジェクト: cryptoatropine/oldlpfw
void parse_command_line(int argc, char* argv[])
{
    // if the parsing of the arguments was unsuccessful
    int nerrors;

    // Define argument table structs
    python_folder = arg_file0 ( NULL, "py-folder", "<path to file>", "Path to folder (relative or absolute) that contains python script (default: lpfw-pygui)" );
    log_debug = arg_int0 ( NULL, "log-debug", "<1/0 for yes/no>", "Enable debug messages logging" );

    struct arg_lit *help = arg_lit0 ( NULL, "help", "Display this help screen" );
    struct arg_lit *version = arg_lit0 ( NULL, "version", "Display the current version" );
    struct arg_end *end = arg_end ( 10 );
    void *argtable[] = {python_folder, log_debug, help, version, end};

    // Set default values
    char *python_folder_pointer = malloc(strlen("lpfw-pygui")+1);
    strcpy (python_folder_pointer, "lpfw-pygui");
    python_folder->filename[0] = python_folder_pointer;

    * ( log_debug->ival ) = 0;

    if ( arg_nullcheck ( argtable ) != 0 )
      {
	printf ( "Error: insufficient memory\n" );
	exit(0);
      }

    nerrors = arg_parse ( argc, argv, argtable );

    if ( nerrors == 0 )
      {
	if ( help->count == 1 )
	  {
	    printf ( "Leopard Flower frontend :\n Syntax and help:\n" );
	    arg_print_glossary ( stdout, argtable, "%-43s %s\n" );
	    exit (0);
	  }
	else if ( version->count == 1 )
	  {
	    printf ( "%s\n", VERSION );
	    exit (0);
	  }
    }
    else if ( nerrors > 0 )
      {
	arg_print_errors ( stdout, end, "Leopard Flower frontend" );
	printf ( "Leopard Flower frontend:\n Syntax and help:\n" );
	arg_print_glossary ( stdout, argtable, "%-43s %s\n" );
	exit (1);
      }

    // Free memory - don't do this cause args needed later on
    //  arg_freetable(argtable, sizeof (argtable) / sizeof (argtable[0]));
}
コード例 #11
0
ファイル: cmd_wifi.c プロジェクト: danathughes/esp-idf
static int wifi_cmd_sta(int argc, char** argv)
{
    int nerrors = arg_parse(argc, argv, (void**) &sta_args);

    if (nerrors != 0) {
        arg_print_errors(stderr, sta_args.end, argv[0]);
        return 1;
    }

    ESP_LOGI(TAG, "sta connecting to '%s'", sta_args.ssid->sval[0]);
    wifi_cmd_sta_join(sta_args.ssid->sval[0], sta_args.password->sval[0]);
    return 0;
}
コード例 #12
0
ファイル: sesh.c プロジェクト: artemsmirnov/sesh
int main(int argc, char *argv[]) {
	/* Name of the programme */
	char progname[] = "sesh";
	char progversion[] = "0.4.0";

	/* Arguments table */
	void *argtable[] = {
		help    = arg_litn("h", "help", 0, 1, "Display this help and exit"),
		version = arg_litn("v", "version", 0, 1, "Display version info and exit"),
		end     = arg_end(20),
	};

	/* Number of errors analysing arguments */
	int nerrors = arg_parse(argc, argv, argtable);

	/* If help needed we don't care about the errors */
	if (help->count > 0) {
		printf("Usage: %s", progname);
		arg_print_syntax(stdout, argtable, "\n");
		arg_print_glossary(stdout, argtable, "  %-25s %s\n");
		
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 0;
	}

	/* If errors occured */
	if (nerrors > 0) {
		/* Displaying the error information */
		arg_print_errors(stdout, end, progname);
		printf("Try '%s --help' for more information.\n", progname);
		
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	if (version->count > 0) {
		printf("Version: %s %s\n", progname, progversion);

		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 0;
	}

	history_init();
	term_set_driver();
	repl();	
	term_reset_driver();

	arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
	return 0;
}
コード例 #13
0
int main(int argc, char * argv[]) {
    void* argtable[] = {
                input = arg_filen(   "i",   "input",              "<string>", 0, 100,    "input file")
        ,  o_validate = arg_strn(   "v",  "validate",     "<string>",         0, 10,   "validate operations")
        ,         o_h = arg_file0(   NULL,  "output-h",           "<string>",            "output h file dir")
        ,     o_lib_c = arg_file0(   NULL,  "output-lib-c",       "<string>",            "output c lib file")
        , o_lib_c_arg = arg_str0(   NULL,  "output-lib-c-arg",    "<string>",            "output c lib file")
        ,   o_lib_bin = arg_file0(   NULL,  "output-lib-bin",     "<string>",            "output c lib file")
        ,        help = arg_lit0(   NULL,  "help",                                   "print this help and exit")
        ,         end = arg_end(20)
    };

    struct error_monitor em_buf;
    error_monitor_t em;
    int rv;
    int nerrors;

    cpe_error_monitor_init(&em_buf, cpe_error_log_to_consol, 0);
    em = &em_buf;

    rv = -1;

    if (arg_nullcheck(argtable) != 0) {
        CPE_ERROR(em, "init arg table fail!");
        goto exit;
    }

    nerrors = arg_parse(argc,argv,argtable);

    if (help->count > 0) {
        printf("Usage: %s", argv[0]);
        arg_print_syntax(stdout,argtable,"\n");
        rv = 0;
        goto exit;
    }

    if (nerrors > 0) {
        arg_print_errors(stdout, end, argv[0]);
        printf("Try '%s --help' for more information.\n", argv[0]);
        goto exit;
    }

    rv = tools_main(em);

exit:
    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));

    return rv;
}
コード例 #14
0
ファイル: testargtable3.c プロジェクト: argtable/argtable3
int main(int argc, char *argv[])
{
    /* the global arg_xxx structs are initialised within the argtable */
    void *argtable[] = {
        help    = arg_lit0(NULL, "help", "display this help and exit"),
        version = arg_lit0(NULL, "version", "display version info and exit"),
        a       = arg_lit0("a", NULL,"the -a option"),
        b       = arg_lit0("b", NULL, "the -b option"),
        c       = arg_lit0("c", NULL, "the -c option"),
        scal    = arg_int0(NULL, "scalar", "<n>", "foo value"),
        verb    = arg_lit0("v", "verbose", "verbose output"),
        o       = arg_file0("o", NULL, "myfile", "output file"),
        file    = arg_filen(NULL, NULL, "<file>", 0, 100, "input files"),
        end     = arg_end(20),
    };

    int exitcode = 0;
    char progname[] = "testargtable3.exe";

    int nerrors;
    nerrors = arg_parse(argc,argv,argtable);

    /* special case: '--help' takes precedence over error reporting */
    if (help->count > 0)
    {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout, argtable, "\n");
        printf("List information about the FILE(s) "
               "(the current directory by default).\n\n");
        arg_print_glossary(stdout, argtable, "  %-25s %s\n");
        exitcode = 0;
        goto exit;
    }

    /* If the parser returned any errors then display them and exit */
    if (nerrors > 0)
    {
        /* Display the error details contained in the arg_end struct.*/
        arg_print_errors(stdout, end, progname);
        printf("Try '%s --help' for more information.\n", progname);
        exitcode = 1;
        goto exit;
    }

exit:
    /* deallocate each non-null entry in argtable[] */
    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
    return exitcode;
}
コード例 #15
0
ファイル: RXE.c プロジェクト: LasseSkogland/RXE
/*
 * All code below is "unimportant", it's only argument and file handling
 */
int main(int argc, char *argv[]) {
	struct arg_file *ifile = arg_file1("i", "input-file", "INPUT_FILE", "Set Input File");
	struct arg_file *ofile = arg_file0("o", "output-file", "OUTPUT_FILE", "Set Output File");
	struct arg_str *pass = arg_str0("p", "password", "PASSWORD", "Set Encryption Password");
	struct arg_int *pas = arg_int0("c", "passes", "PASSES", "Set number of passes (To decrypt you'll need the same number of passes)");
	struct arg_int *buf = arg_int0("b", "buffer-size", "BUFFER_SIZE", "Set Buffer Size");
	struct arg_end *end = arg_end(20);
	void *argtable[] = {
	ifile, ofile, pass, pas, buf, end};
	int nerrors = arg_parse(argc, argv, argtable);
	
	if (nerrors > 0) {
		arg_print_errors(stdout, end, "rxe");
		printf("\nUsage: rxe");
		arg_print_syntax(stdout, argtable, "\n");
		arg_print_glossary(stdout, argtable, "  %-10s %s\n");
	} else {
		if (buf->count > 0) {
			BUFFER_SIZE = buf->ival[0];
		}
		FILE *outfile, *infile = fopen(ifile->filename[0], "rb");
		if (ofile->count > 0) outfile = fopen(ofile->filename[0], "wb");
		else {
			char farr[2048];
			char *ptr;
			strcpy(farr, ifile->filename[0]);
			if ((ptr = strstr(farr, ".rxe")) != NULL) {
				farr[0] = '\0';
				farr[1] = '\0';
				farr[2] = '\0';
				farr[3] = '\0';
			} else strcat(farr, ".rxe");
			outfile = fopen(farr, "wb");
		}
		if(pas->count > 0) PASSES = pas->ival[0];
		if(pass->count > 0) RXE_Main(infile, outfile, (char *)pass->sval[0]);
		else RXE_Main(infile, outfile, "DEFAULT");
		fclose(outfile);
		fclose(infile);
	}
	return 0;
}
コード例 #16
0
ファイル: main.c プロジェクト: jathd/DCPUToolchain
int main(int argc, char* argv[])
{
    // Define our variables.
    int nerrors, i;
    int32_t saved = 0; // The number of words saved during compression and optimization.
    struct errinfo* errval;
    const char* prepend = "error: ";
    const char* warnprefix = "no-";
    int msglen;
    char* msg;
    int target;

    // Define arguments.
    struct arg_lit* show_help = arg_lit0("h", "help", "Show this help.");
    struct arg_str* target_arg = arg_str0("l", "link-as", "target", "Link as the specified object, can be 'image', 'static' or 'kernel'.");
    struct arg_file* symbol_file = arg_file0("s", "symbols", "<file>", "Produce a combined symbol file (~triples memory usage!).");
    struct arg_str* symbol_ext = arg_str0(NULL, "symbol-extension", "ext", "When -s is used, specifies the extension for symbol files.  Defaults to \"dsym16\".");
    struct arg_file* input_files = arg_filen(NULL, NULL, "<file>", 1, 100, "The input object files.");
    struct arg_file* output_file = arg_file1("o", "output", "<file>", "The output file (or - to send to standard output).");
    struct arg_file* kernel_file = arg_file0("k", "kernel", "<file>", "Directly link in the specified kernel.");
    struct arg_file* jumplist_file = arg_file0("j", "jumplist", "<file>", "Link against the specified jumplist.");
    struct arg_str* warning_policies = arg_strn("W", NULL, "policy", 0, _WARN_COUNT * 2 + 10, "Modify warning policies.");
    struct arg_lit* keep_output_arg = arg_lit0(NULL, "keep-outputs", "Keep the .OUTPUT entries in the final static library (used for stdlib).");
    struct arg_lit* little_endian_mode = arg_lit0(NULL, "little-endian", "Use little endian serialization (for compatibility with older versions).");
    struct arg_lit* no_short_literals_arg = arg_lit0(NULL, "no-short-literals", "Do not compress literals to short literals.");
    struct arg_int* opt_level = arg_int0("O", NULL, "<level>", "The optimization level.");
    struct arg_lit* opt_mode = arg_lit0("S", NULL, "Favour runtime speed over size when optimizing.");
    struct arg_lit* verbose = arg_litn("v", NULL, 0, LEVEL_EVERYTHING - LEVEL_DEFAULT, "Increase verbosity.");
    struct arg_lit* quiet = arg_litn("q", NULL,  0, LEVEL_DEFAULT - LEVEL_SILENT, "Decrease verbosity.");
    struct arg_end* end = arg_end(20);
    void* argtable[] = { show_help, target_arg, keep_output_arg, little_endian_mode, opt_level, opt_mode, no_short_literals_arg,
                         symbol_ext, symbol_file, kernel_file, jumplist_file, warning_policies, output_file, input_files, verbose, quiet, end
                       };

    // Parse arguments.
    nerrors = arg_parse(argc, argv, argtable);

    version_print(bautofree(bfromcstr("Linker")));
    if (nerrors != 0 || show_help->count != 0)
    {
        if (show_help->count != 0)
            arg_print_errors(stdout, end, "linker");

        printd(LEVEL_DEFAULT, "syntax:\n    dtld");
        arg_print_syntax(stderr, argtable, "\n");
        printd(LEVEL_DEFAULT, "options:\n");
        arg_print_glossary(stderr, argtable, "    %-25s %s\n");
        arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
        return 1;
    }

    // Set verbosity level.
    debug_setlevel(LEVEL_DEFAULT + verbose->count - quiet->count);

    // Set global path variable.
    osutil_setarg0(bautofree(bfromcstr(argv[0])));

    // Set endianness.
    isetmode(little_endian_mode->count == 0 ? IMODE_BIG : IMODE_LITTLE);

    // Set up warning policies.
    dsetwarnpolicy(warning_policies);

    // Set up error handling.
    if (dsethalt())
    {
        errval = derrinfo();

        // FIXME: Use bstrings here.
        msglen = strlen(derrstr[errval->errid]) + strlen(prepend) + 1;
        msg = malloc(msglen);
        memset(msg, '\0', msglen);
        strcat(msg, prepend);
        strcat(msg, derrstr[errval->errid]);
        printd(LEVEL_ERROR, msg, errval->errdata);

        // Handle the error.
        printd(LEVEL_ERROR, "linker: error occurred.\n");

        arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
        return 1;
    }

    // Check to make sure target is correct.
    if (target_arg->count == 0)
        target = IMAGE_APPLICATION;
    else
    {
        if (strcmp(target_arg->sval[0], "image") == 0)
            target = IMAGE_APPLICATION;
        else if (strcmp(target_arg->sval[0], "static") == 0)
            target = IMAGE_STATIC_LIBRARY;
        else if (strcmp(target_arg->sval[0], "kernel") == 0)
            target = IMAGE_KERNEL;
        else
        {
            // Invalid option.
            dhalt(ERR_INVALID_TARGET_NAME, NULL);
        }
    }

    // Load all passed objects and use linker bin system to
    // produce result.
    bins_init();
    for (i = 0; i < input_files->count; i++)
        if (!bins_load(bautofree(bfromcstr(input_files->filename[i])), symbol_file->count > 0, (symbol_file->count > 0 && symbol_ext->count > 0) ? symbol_ext->sval[0] : "dsym16"))
            // Failed to load one of the input files.
            dhalt(ERR_BIN_LOAD_FAILED, input_files->filename[i]);
    bins_associate();
    bins_sectionize();
    bins_flatten(bautofree(bfromcstr("output")));
    if (target == IMAGE_KERNEL)
        bins_write_jump();
    saved = bins_optimize(
                opt_mode->count == 0 ? OPTIMIZE_SIZE : OPTIMIZE_SPEED,
                opt_level->count == 0 ? OPTIMIZE_NONE : opt_level->ival[0]);
    if (no_short_literals_arg->count == 0 && target != IMAGE_STATIC_LIBRARY)
        saved += bins_compress();
    else if (no_short_literals_arg->count == 0)
        dwarn(WARN_SKIPPING_SHORT_LITERALS_TYPE, NULL);
    else
        dwarn(WARN_SKIPPING_SHORT_LITERALS_REQUEST, NULL);
    bins_resolve(
        target == IMAGE_STATIC_LIBRARY,
        target == IMAGE_STATIC_LIBRARY);
    bins_save(
        bautofree(bfromcstr("output")),
        bautofree(bfromcstr(output_file->filename[0])),
        target,
        keep_output_arg->count > 0,
        symbol_file->count > 0 ? symbol_file->filename[0] : NULL,
        jumplist_file->count > 0 ? jumplist_file->filename[0] : NULL);
    bins_free();
    if (saved > 0)
        printd(LEVEL_DEFAULT, "linker: saved %i words during optimization.\n", saved);
    else if (saved < 0)
        printd(LEVEL_DEFAULT, "linker: increased by %i words during optimization.\n", -saved);

    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
    return 0;
}
コード例 #17
0
int
main(int argc, char **argv)
{
    struct arg_int *channels  = arg_int0("c", "channels", "<n>", "define number of channels (default is 1)");
    struct arg_int *subscribers  = arg_int0("s", "subscribers", "<n>", "define number of subscribers (default is 1)");

    struct arg_str *server_name = arg_str0("S", "server", "<hostname>", "server hostname where messages will be published (default is \"127.0.0.1\")");
    struct arg_int *server_port = arg_int0("P", "port", "<n>", "server port where messages will be published (default is 9080)");

    struct arg_int *timeout = arg_int0(NULL, "timeout", "<n>", "timeout when waiting events on communication to the server (default is 1000)");
    struct arg_int *verbose = arg_int0("v", "verbose", "<n>", "increase output messages detail (0 (default) - no messages, 1 - info messages, 2 - debug messages, 3 - trace messages");

    struct arg_lit *help    = arg_lit0(NULL, "help", "print this help and exit");
    struct arg_lit *version = arg_lit0(NULL, "version", "print version information and exit");
    struct arg_end *end     = arg_end(20);

    void* argtable[] = { channels, subscribers, server_name, server_port, timeout, verbose, help, version, end };

    const char* progname = "subscriber";
    int nerrors;
    int exitcode = EXIT_SUCCESS;

    /* verify the argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable) != 0) {
        /* NULL entries were detected, some allocations must have failed */
        printf("%s: insufficient memory\n", progname);
        exitcode = EXIT_FAILURE;
        goto exit;
    }

    /* set any command line default values prior to parsing */
    subscribers->ival[0] = DEFAULT_CONCURRENT_CONN;
    channels->ival[0] = DEFAULT_NUM_CHANNELS;
    server_name->sval[0] = DEFAULT_SERVER_HOSTNAME;
    server_port->ival[0] = DEFAULT_SERVER_PORT;
    timeout->ival[0] = DEFAULT_TIMEOUT;
    verbose->ival[0] = 0;

    /* Parse the command line as defined by argtable[] */
    nerrors = arg_parse(argc, argv, argtable);

    /* special case: '--help' takes precedence over error reporting */
    if (help->count > 0) {
        printf(DESCRIPTION_SUBSCRIBER, progname, VERSION, COPYRIGHT);
        printf("Usage: %s", progname);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_glossary(stdout, argtable, "  %-25s %s\n");
        exitcode = EXIT_SUCCESS;
        goto exit;
    }

    /* special case: '--version' takes precedence error reporting */
    if (version->count > 0) {
        printf(DESCRIPTION_SUBSCRIBER, progname, VERSION, COPYRIGHT);
        exitcode = EXIT_SUCCESS;
        goto exit;
    }

    /* If the parser returned any errors then display them and exit */
    if (nerrors > 0) {
        /* Display the error details contained in the arg_end struct.*/
        arg_print_errors(stdout, end, progname);
        printf("Try '%s --help' for more information.\n", progname);
        exitcode = EXIT_FAILURE;
        goto exit;
    }

    verbose_messages = verbose->ival[0];

    /* normal case: take the command line options at face value */
    exitcode = main_program(channels->ival[0], subscribers->ival[0], server_name->sval[0], server_port->ival[0], timeout->ival[0]);

exit:
    /* deallocate each non-null entry in argtable[] */
    arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));

    return exitcode;
}
コード例 #18
0
int UHD_SAFE_MAIN(int argc, char *argv[]){
    
    uhd::set_thread_priority_safe(); 
   
    size_t rxshm_size, txshm_size;

    bool mimic_active;
    float mimic_delay;

    unsigned int iSide, iSwing; // often used loop variables

    int32_t rx_worker_status = 0; 
    int32_t clrfreq_rx_worker_status = 0; 
    int32_t mute_output = 0; // used if rx_worker error happends

    int32_t rx_stream_reset_count = 0;
    int32_t rx_stream_error_count = 0;

    std::vector<sem_t>  sem_rx_vec(nSwings), sem_tx_vec(nSwings);

    std::vector<uint32_t> state_vec(nSwings, ST_INIT);
    uint32_t swing; // = SWING0;
    
    size_t nSamples_rx, nSamples_tx_pulse, nSamples_pause_after_rx, nSamples_auto_clear_freq, nSamples_rx_total;
    size_t auto_clear_freq_available = 0;


    uint32_t npulses, nerrors;
    ssize_t cmd_status;
    uint32_t usrp_driver_base_port, ip_part;

    int32_t connect_retrys = MAX_SOCKET_RETRYS; 
    int32_t sockopt;
    struct sockaddr_in sockaddr;
    struct sockaddr_storage client_addr;
    socklen_t addr_size;
    uint32_t exit_driver = 0;

    uint32_t tx_worker_active;

    uhd::time_spec_t start_time, rx_start_time;

    // vector of all pulse start times over an integration period
    std::vector<uhd::time_spec_t> pulse_time_offsets;
    // vector of the sample index of pulse start times over an integration period
    std::vector<uint64_t> pulse_sample_idx_offsets;

    boost::thread_group uhd_threads;
    boost::thread_group clrfreq_threads;

    // process config file for port and SHM sizes
    DEBUG_PRINT("USRP_DRIVER starting to read driver_config.ini\n");
    boost::property_tree::ptree pt;
    boost::property_tree::ini_parser::read_ini("../driver_config.ini", pt);

  //  DEBUG_PRINT("USRP_DRIVER reading rxshm_size\n");
  //  std::cout << pt.get<std::string>("shm_settings.rxshm_size") << '\n';
    rxshm_size = std::stoi(pt.get<std::string>("shm_settings.rxshm_size"));
 
  //  DEBUG_PRINT("USRP_DRIVER reading txshm_size\n");
    txshm_size = std::stoi(pt.get<std::string>("shm_settings.txshm_size"));

    usrp_driver_base_port = std::stoi(pt.get<std::string>("network_settings.USRPDriverPort"));
    
    boost::property_tree::ptree pt_array;
    DEBUG_PRINT("USRP_DRIVER starting to read array_config.ini\n");
    boost::property_tree::ini_parser::read_ini("../array_config.ini", pt_array);
    mimic_active = std::stof(pt_array.get<std::string>("mimic.mimic_active")) != 0;
    mimic_delay  = std::stof(pt_array.get<std::string>("mimic.mimic_delay"));
    fprintf(stderr, "read from ini: mimic_active=%d, mimic_delay=%f\n", mimic_active, mimic_delay);

    init_all_dirs();

    // TODO also read usrp_config.ini and get antenna and side information from it. remove antenna input argument. 

    // process command line arguments
    struct arg_lit  *al_help   = arg_lit0(NULL, "help", "Prints help information and then exits");
//    struct arg_int  *ai_ant    = arg_intn("a", "antenna", NULL, 1, 2, "Antenna position index for the USRP"); 
    struct arg_int  *ai_ant_a          = arg_int0("a", "antennaA", NULL, "Antenna position index for the USRP on side A"); 
    struct arg_int  *ai_ant_b          = arg_int0("b", "antennaB", NULL, "Antenna position index for the USRP on side B"); 
    struct arg_str  *as_host           = arg_str0("h", "host", NULL, "Hostname or IP address of USRP to control (e.g usrp1)"); 
    struct arg_lit  *al_intclk         = arg_lit0("i", "intclk", "Select internal clock (default is external)"); 
    struct arg_lit  *al_interferometer = arg_lit0("x", "interferometer", "Disable tx_worker for interferometer antennas"); 
    struct arg_end  *ae_argend         = arg_end(ARG_MAXERRORS);
    void* argtable[] = {al_help, ai_ant_a, ai_ant_b, as_host, al_intclk, al_interferometer, ae_argend};
    
    double txrate, rxrate, txfreq, rxfreq;
    double txrate_new, rxrate_new, txfreq_new, rxfreq_new;

    DEBUG_PRINT("usrp_driver debug mode enabled\n");

    if (SUPRESS_UHD_PRINTS) {
        uhd::msg::register_handler(&uhd_term_message_handler);
    }

    nerrors = arg_parse(argc,argv,argtable);
    if (nerrors > 0) {
        arg_print_errors(stdout,ae_argend,"usrp_driver");
        exit(1);
    }
    if (argc == 1) {
        printf("No arguments found, try running again with --help for more information.\n");
        exit(1);
    }
    if(al_help->count > 0) {
        printf("Usage: ");
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
        arg_freetable(argtable, sizeof(argtable)/sizeof(argtable[0]));
        return 0;
    }
   
    unsigned int nSides =  ai_ant_a->count + ai_ant_b->count; 
    if( nSides == 0 ) {
        printf("No antenna index, exiting...");
        return 0;
    }
    
    if(as_host->sval == NULL) {
        printf("Missing usrp host command line argument, exiting...");
        return 0;
    }

    std::vector<int> antennaVector(nSides);
    std::vector<uint64_t> channel_numbers;
    // both sides
    if( nSides == 2 ) {
        DEBUG_PRINT("Setting side A: ant_idx %d\n",ai_ant_a->ival[0]);
        antennaVector[0] = ai_ant_a->ival[0];
        channel_numbers.push_back(0);

        DEBUG_PRINT("Setting side B: ant_idx %d\n",ai_ant_b->ival[0]);
        antennaVector[1] = ai_ant_b->ival[0];
        channel_numbers.push_back(1);
    } else {
     // side A
     if (ai_ant_a->count == 1) {
        DEBUG_PRINT("Setting side A: ant_idx %d\n",ai_ant_a->ival[0]);
        antennaVector[0] = ai_ant_a->ival[0];
        channel_numbers.push_back(0);
     // side B
     } else {
        DEBUG_PRINT("Setting side B: ant_idx %d\n",ai_ant_b->ival[0]);
        antennaVector[0] = ai_ant_b->ival[0];
        channel_numbers.push_back(1);
        DEBUG_PRINT("Warning: For one side use DIO output is always on Side A!!!!!!!!!!!!!"); // TODO correct this


     }

    }

    // pointers to shared memory
    std::vector<std::vector<void *>> shm_rx_vec(nSides, std::vector<void *>( nSwings));
    std::vector<std::vector<void *>> shm_tx_vec(nSides, std::vector<void *>( nSwings));

    // local buffers for tx and rx
    std::vector<std::vector<std::complex<int16_t>>> tx_samples(nSides,         std::vector<std::complex<int16_t>>(MAX_PULSE_LENGTH,0));
    std::vector<std::vector<std::complex<int16_t>>> rx_data_buffer(nSides,     std::vector<std::complex<int16_t>>(0));
    std::vector<std::vector<std::complex<int16_t>>> rx_auto_clear_freq(nSides, std::vector<std::complex<int16_t>>(0));
     

    std::string usrpargs(as_host->sval[0]);
    usrpargs = "addr0=" + usrpargs + ",master_clock_rate=200.0e6";
//    usrpargs = "addr0=" + usrpargs + ",master_clock_rate=200.0e6,recv_frame_size=50000000";
    uhd::usrp::multi_usrp::sptr usrp = uhd::usrp::multi_usrp::make(usrpargs);
  //  usrp->set_rx_subdev_spec(uhd::usrp::subdev_spec_t("A:A B:A"));
  //  usrp->set_tx_subdev_spec(uhd::usrp::subdev_spec_t("A:A B:A"));
    boost::this_thread::sleep(boost::posix_time::seconds(SETUP_WAIT));
    uhd::stream_args_t stream_args("sc16", "sc16");
    
    if (usrp->get_rx_num_channels() < nSides || usrp->get_tx_num_channels() < nSides) {  
       DEBUG_PRINT("ERROR: Number of defined channels (%i) is smaller than avaialable channels:\n    usrp->get_rx_num_channels(): %lu \n    usrp->get_tx_num_channels(): %lu \n\n", nSides, usrp->get_rx_num_channels(),   usrp->get_tx_num_channels());
       return -1;
    }
    stream_args.channels = channel_numbers;
    uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);
    uhd::tx_streamer::sptr tx_stream = usrp->get_tx_stream(stream_args);


    // TODO: retry uhd connection if fails..

    // Determine port from 3rd part of ip (192.168.x.2 => port = base_port + x ) 
    int start_idx = usrpargs.find("."); 
    start_idx = usrpargs.find(".", start_idx+1);
    int end_idx = usrpargs.find(".", start_idx+1);
    ip_part = atoi(usrpargs.substr(start_idx+1, end_idx-start_idx-1).c_str());



    // initialize rxfe gpio
    kodiak_init_rxfe(usrp, nSides);
    // initialize other gpio on usrp
    init_timing_signals(usrp, mimic_active, nSides);
    
    //if(CAPTURE_ERRORS) {
    //    signal(SIGINT, siginthandler);
    //}
    
    // open shared memory buffers and semaphores created by cuda_driver.py
    // for dual polarization we use antenna numbers 20 to 35 (side is always 0)
    for(iSwing = 0; iSwing < nSwings; iSwing++) {
        for(iSide = 0; iSide < nSides; iSide++) {
            int shm_side = 0;
            shm_rx_vec[iSide][iSwing] = open_sample_shm(antennaVector[iSide], RXDIR, shm_side, iSwing, rxshm_size);
            shm_tx_vec[iSide][iSwing] = open_sample_shm(antennaVector[iSide], TXDIR, shm_side, iSwing, txshm_size);
            DEBUG_PRINT("usrp_driver rx shm addr: %p iSide: %d iSwing: %d\n", shm_rx_vec[iSide][iSwing], iSide, iSwing);

            if (antennaVector[iSide] < 19 ) { // semaphores only for antennas of first polarization TODO check if this is enough
               sem_rx_vec[iSwing] = open_sample_semaphore(antennaVector[iSide], iSwing, RXDIR);
               sem_tx_vec[iSwing] = open_sample_semaphore(antennaVector[iSide], iSwing, TXDIR);
            }
        }
    }

    if(al_interferometer->count > 0) {
       DEBUG_PRINT("Disable tx_worker ...\n");
       tx_worker_active = 0;
    } else {
       tx_worker_active = 1;
    }

    if(al_intclk->count > 0) {
        usrp->set_clock_source("internal");
        usrp->set_time_source("internal");
    }
    else {
    // sync clock with external 10 MHz and PPS
        DEBUG_PRINT("Set clock: external\n");
        usrp->set_clock_source("external", 0);
        DEBUG_PRINT("Set time: external\n");
        usrp->set_time_source("external", 0);
        DEBUG_PRINT("Done setting time and clock\n");
     }

    while(true) {
        if(driversock) {
            close(driverconn);
            close(driversock);
        }
   
        boost::this_thread::sleep(boost::posix_time::seconds(SETUP_WAIT));

        // bind to socket for communication with usrp_server.py:
        driversock = socket(AF_INET, SOCK_STREAM, 0);
        if(driversock < 0){
            perror("opening stream socket\n");
            exit(1);
        }

        sockopt = 1;
        setsockopt(driversock, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(int32_t));

        sockaddr.sin_family = AF_INET;
        // TODO: maybe limit addr to interface connected to usrp_server
        sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);

        fprintf(stderr, "listening on port: %d\n", usrp_driver_base_port + ip_part); 
        sockaddr.sin_port = htons(usrp_driver_base_port + ip_part);
        

        if( bind(driversock, (struct sockaddr *)&sockaddr, sizeof(sockaddr)) < 0){
                perror("binding tx stream socket");
                exit(1);
        }
   
        // wait for connection...
        listen(driversock, 5);

        // and accept it
        fprintf(stderr, "waiting for socket connection\n");
        addr_size = sizeof(client_addr);
        driverconn = accept(driversock, (struct sockaddr *) &client_addr, &addr_size);
        fprintf(stderr, "accepted socket connection\n");



        while(true) {
            // wait for transport endpoint to connect?
            
            DEBUG_PRINT("USRP_DRIVER waiting for command\n");
            uint8_t command = sock_get_cmd(driverconn, &cmd_status);
            DEBUG_PRINT("USRP_DRIVER received command, status: %zu\n", cmd_status);
             
            // see if socket is closed..
            if(cmd_status == 11 || cmd_status == 0 || cmd_status < 0) {
                DEBUG_PRINT("USRP_DRIVER lost connection to usrp_server, waiting for fresh connection, %d tries remaining\n", connect_retrys);
                close(driversock);
                if(connect_retrys-- < 0) {
                    exit(1);
                }
                sleep(1);
                break;
            }

            connect_retrys = MAX_SOCKET_RETRYS;


            switch(command) {
                case USRP_SETUP: {
                    // receive infomation about a pulse sequence/integration period
                    // transmit/receive center frequenies and sampling rates
                    // number of tx/rx samples
                    // number of pulse sequences per integration period, and pulse start times
                    
                    swing      = sock_get_int16(  driverconn); 
                    
                    DEBUG_PRINT("entering USRP_SETUP command (swing %d)\n", swing);
                  
                    txfreq_new = sock_get_float64(driverconn);
                    rxfreq_new = sock_get_float64(driverconn);
                    txrate_new = sock_get_float64(driverconn);
                    rxrate_new = sock_get_float64(driverconn);

                    npulses = sock_get_uint32(driverconn);

                    nSamples_rx              = sock_get_uint64(driverconn);
                    nSamples_pause_after_rx  = sock_get_uint64(driverconn);
                    nSamples_auto_clear_freq = sock_get_uint64(driverconn);
                    nSamples_tx_pulse        = sock_get_uint64(driverconn);
                    nSamples_rx_total        = nSamples_rx + nSamples_pause_after_rx + nSamples_auto_clear_freq;

                    DEBUG_PRINT("USRP_SETUP number of requested rx samples: %d + %d pause + %d auto clear freq\n", (uint32_t) nSamples_rx, nSamples_pause_after_rx, nSamples_auto_clear_freq);
                    DEBUG_PRINT("USRP_SETUP number of requested tx samples per pulse: %d\n", (uint32_t) nSamples_tx_pulse);
                    DEBUG_PRINT("USRP_SETUP existing tx rate : %f (swing %d)\n", txrate, swing);
                    DEBUG_PRINT("USRP_SETUP requested tx rate: %f\n", txrate_new);

                    // resize 
                    pulse_sample_idx_offsets.resize(npulses);
                    pulse_time_offsets.resize(npulses);

                    for(uint32_t i = 0; i < npulses; i++) {
                //        DEBUG_PRINT("USRP_SETUP waiting for pulse offset %d of %d\n", i+2, npulses);
                        pulse_sample_idx_offsets[i] = sock_get_uint64(driverconn); 
                //        DEBUG_PRINT("USRP_SETUP received %zu pulse offset\n", pulse_sample_idx_offsets[i]);

                    }
                    DEBUG_PRINT("USRP_SETUP resize autoclear freq\n");

                    // RESIZE LOCAL BUFFERS
                    if(rx_data_buffer[0].size() < nSamples_rx_total) {
                       for(iSide = 0; iSide < nSides; iSide++) {
                           rx_data_buffer[iSide].resize(nSamples_rx_total);
                       }
                    }
                    DEBUG_PRINT("USRP_SETUP resize autoclear freq\n");

                    if(nSamples_auto_clear_freq != 0 and rx_auto_clear_freq[0].size() < nSamples_auto_clear_freq) {
                       for(iSide = 0; iSide < nSides; iSide++) {
                           rx_auto_clear_freq[iSide].resize(nSamples_auto_clear_freq);
                       }
                    }

                    // TODO use return argument of set_xx to save new rate/freq                    
   
                    // if necessary, retune USRP frequency and sampling rate
                    if(rxrate != rxrate_new) {
                       usrp->set_rx_rate(rxrate_new);
                       rxrate = usrp->get_rx_rate();
                    }

                    if(txrate != txrate_new) {
                       usrp->set_tx_rate(txrate_new);
                       txrate = usrp->get_tx_rate();
                    }

                    if(rxfreq != rxfreq_new) {
                       for(iSide = 0; iSide < nSides; iSide++) {
                          usrp->set_rx_freq(rxfreq_new, iSide);
                       }
                       rxfreq = usrp->get_rx_freq();
                    }

                    if(txfreq != txfreq_new) {
                       for(iSide = 0; iSide < nSides; iSide++) {
                          usrp->set_tx_freq(txfreq_new, iSide);
                       }
                       txfreq = usrp->get_tx_freq();
                    }

                    if(verbose) {
                        std::cout << boost::format("Actual RX Freq: %f MHz...") % (usrp->get_rx_freq()/1e6)  <<  std::endl;
                        std::cout << boost::format("Actual RX Rate: %f Msps...") % (usrp->get_rx_rate()/1e6) <<  std::endl;
                        std::cout << boost::format("Actual TX Freq: %f MHz...") % (usrp->get_tx_freq()/1e6)  <<  std::endl;
                        std::cout << boost::format("Actual TX Rate: %f Msps...") % (usrp->get_tx_rate()/1e6) <<  std::endl;
                    }

                    // TODO: set the number of samples in a pulse. this is calculated from the pulse duration and the sampling rate 
                    // when do we know this? after USRP_SETUP
                
                    // create local copy of transmit pulse data from shared memory
                    std::complex<int16_t> *shm_pulseaddr;
                    size_t spb = tx_stream->get_max_num_samps();
                    size_t pulse_bytes = sizeof(std::complex<int16_t>) * nSamples_tx_pulse;
                    size_t number_of_pulses = pulse_time_offsets.size();
                    size_t num_samples_per_pulse_with_padding = nSamples_tx_pulse + 2*spb;
                    DEBUG_PRINT("spb %d, pulse length %d samples, pulse with padding %d\n", spb, nSamples_tx_pulse, num_samples_per_pulse_with_padding);

                    // TODO unpack and pad tx sample
                    for (iSide = 0; iSide<nSides; iSide++) {
                        tx_samples[iSide].resize(number_of_pulses * (num_samples_per_pulse_with_padding));                   

                        for(uint32_t p_i = 0; p_i < number_of_pulses; p_i++) {
                            shm_pulseaddr = &((std::complex<int16_t> *) shm_tx_vec[iSide][swing])[p_i*nSamples_tx_pulse];
                            memcpy(&tx_samples[iSide][spb + p_i*(num_samples_per_pulse_with_padding)], shm_pulseaddr, pulse_bytes);
                        }
                    }


                    if(SAVE_RAW_SAMPLES_DEBUG) {
                        FILE *raw_dump_fp;
                        char raw_dump_name[80];
                       // DEBUG_PRINT("Exporting %i raw tx_samples (%i + 2* %i)\n", num_samples_per_pulse_with_padding, nSamples_tx_pulse, spb);
                        for (iSide =0; iSide < nSides; iSide++){
                            sprintf(raw_dump_name,"%s/raw_samples_tx_ant_%d.cint16", diag_dir, antennaVector[iSide]);
                            raw_dump_fp = fopen(raw_dump_name, "wb");
                            fwrite(&tx_samples[iSide][0], sizeof(std::complex<int16_t>),num_samples_per_pulse_with_padding*number_of_pulses, raw_dump_fp);
                            fclose(raw_dump_fp);
                        }
                    }


                    state_vec[swing] = ST_READY; 
                    DEBUG_PRINT("changing state_vec[swing] to ST_READY\n");
                    sock_send_uint8(driverconn, USRP_SETUP);
                    break;
                    }

                case RXFE_SET: {
                    DEBUG_PRINT("entering RXFE_SET command\n");
                    RXFESettings rf_settings;
                    rf_settings.amp1 = sock_get_uint8(driverconn);
                    rf_settings.amp2 = sock_get_uint8(driverconn);
                    uint8_t attTimes2 = sock_get_uint8(driverconn);
                    rf_settings.att_05_dB = ( attTimes2 & 0x01 ) != 0;
                    rf_settings.att_1_dB  = ( attTimes2 & 0x02 ) != 0;
                    rf_settings.att_2_dB  = ( attTimes2 & 0x04 ) != 0;
                    rf_settings.att_4_dB  = ( attTimes2 & 0x08 ) != 0;
                    rf_settings.att_8_dB  = ( attTimes2 & 0x10 ) != 0;
                    rf_settings.att_16_dB = ( attTimes2 & 0x20 ) != 0;
                   
                    kodiak_set_rxfe(usrp, rf_settings, nSides);
                    sock_send_uint8(driverconn, RXFE_SET);
                    break;
                    }

                case TRIGGER_PULSE: {

                    swing      = sock_get_int16(  driverconn); 
                    DEBUG_PRINT("entering TRIGGER_PULSE command (swing %d)\n", swing );

                    if (state_vec[swing] != ST_READY) {
                        sock_send_uint8(driverconn, TRIGGER_BUSY);
                        DEBUG_PRINT("TRIGGER_PULSE busy in state_vec[swing] %d, returning\n", state_vec[swing]);
                    }
                    else {

                        DEBUG_PRINT("TRIGGER_PULSE ready\n");
                        state_vec[swing] = ST_PULSE;

                        DEBUG_PRINT("TRIGGER_PULSE locking semaphore\n");
                        lock_semaphore(sem_rx_vec[swing]); 
                        lock_semaphore(sem_tx_vec[swing]); 

                        DEBUG_PRINT("TRIGGER_PULSE semaphore locked\n");

                        // create local copy of transmit pulse data from shared memory
                        size_t spb = tx_stream->get_max_num_samps();
                        size_t pulse_bytes = sizeof(std::complex<int16_t>) * nSamples_tx_pulse;
                        size_t number_of_pulses = pulse_time_offsets.size();
                        size_t num_samples_per_pulse_with_padding = nSamples_tx_pulse + 2*spb;
                        DEBUG_PRINT("spb %d, pulse length %d samples, pulse with padding %d\n", spb, nSamples_tx_pulse, num_samples_per_pulse_with_padding);


                        // read in time for start of pulse sequence over socket
                        uint32_t pulse_time_full = sock_get_uint32(driverconn);
                        double pulse_time_frac = sock_get_float64(driverconn);
                        start_time = uhd::time_spec_t(pulse_time_full, pulse_time_frac);
                        double tr_to_pulse_delay = sock_get_float64(driverconn);

                        
                        // calculate usrp clock time of the start of each pulse over the integration period
                        // so we can schedule the io (perhaps we will have to move io off of the usrp if it can't keep up)
                        for(uint32_t p_i = 0; p_i < number_of_pulses; p_i++) {
                            double offset_time = pulse_sample_idx_offsets[p_i] / txrate;
                            pulse_time_offsets[p_i] = offset_time_spec(start_time, offset_time);
                           // DEBUG_PRINT("TRIGGER_PULSE pulse time %d is %2.5f\n", p_i, pulse_time_offsets[p_i].get_real_secs());
                        }

                        DEBUG_PRINT("first TRIGGER_PULSE time is %2.5f and last is %2.5f\n", pulse_time_offsets[0].get_real_secs(), pulse_time_offsets.back().get_real_secs());

                        rx_start_time = offset_time_spec(start_time, tr_to_pulse_delay/1e6);
                        rx_start_time = offset_time_spec(rx_start_time, pulse_sample_idx_offsets[0]/txrate); 

                        // send_timing_for_sequence(usrp, start_time, pulse_times);
                        double pulseLength = nSamples_tx_pulse / txrate;
                        
                        // float debugt = usrp->get_time_now().get_real_secs();
                        // DEBUG_PRINT("USRP_DRIVER: spawning worker threads at usrp_time %2.4f\n", debugt);

                        DEBUG_PRINT("TRIGGER_PULSE creating rx and tx worker threads on swing %d (nSamples_rx= %d + %d pause + %d auto clear freq )\n", swing,(int) nSamples_rx, nSamples_pause_after_rx, nSamples_auto_clear_freq);
                        // works fine with tx_worker and dio_worker, fails if rx_worker is enabled
                        uhd_threads.create_thread(boost::bind(usrp_rx_worker, usrp, rx_stream, &rx_data_buffer, nSamples_rx_total, rx_start_time, &rx_worker_status));


			useconds_t usecs=1000;
                        if (tx_worker_active) { 
			  usleep(usecs);
			  uhd_threads.create_thread(boost::bind(usrp_tx_worker, tx_stream, &tx_samples, num_samples_per_pulse_with_padding, start_time, pulse_sample_idx_offsets)); 
                        }

			usleep(usecs);
                        uhd_threads.create_thread(boost::bind(send_timing_for_sequence, usrp, start_time,  pulse_time_offsets, pulseLength, mimic_active, mimic_delay, nSides)); 


                        sock_send_uint8(driverconn, TRIGGER_PULSE);

                        uhd_threads.join_all(); // wait for transmit threads to finish, drawn from shared memory..
                        DEBUG_PRINT("TRIGGER_PULSE rx_worker, tx_worker and dio threads on swing %d\n joined.", swing);


                    }


                    break;
                    }

                case READY_DATA: {
                    swing      = sock_get_int16(  driverconn); 
                    DEBUG_PRINT("READY_DATA command (swing %d), waiting for uhd threads to join back\n", swing);

                    
                    DEBUG_PRINT("READY_DATA unlocking swing a semaphore\n");
                    unlock_semaphore(sem_rx_vec[swing]);
                    unlock_semaphore(sem_tx_vec[swing]);
        
                    DEBUG_PRINT("READY_DATA usrp worker threads joined, semaphore unlocked, sending metadata\n");
                    // TODO: handle multiple channels of data.., use channel index to pick correct swath of memory to copy into shm
                  
                   // rx_worker_status =1; //DEBUG
                    
                    if(rx_worker_status){
                      fprintf(stderr, "Error in rx_worker. Setting state to %d.\n", rx_worker_status);
                      state_vec[swing] = rx_worker_status;
                      rx_worker_status = 0;
                      mute_output = 1;
                      rx_stream_error_count++;
                       
                      if (rx_stream_reset_count >= MAX_STREAM_RESETS) {
                          fprintf(stderr, "READY_DATA: shutting down usrp_driver to avoid streamer reset overflow (after %dth reset)\n", rx_stream_reset_count);
                          // send all data to server, clean up and exit after that
                          exit_driver = 1;
                      }

                      if((rx_worker_status != RX_WORKER_STREAM_TIME_ERROR) && (rx_stream_error_count > 4)) {
                          // recreate rx_stream unless the error was from sending the stream command too late
                          rx_stream_reset_count++;
                          fprintf(stderr, "READY_DATA: recreating rx_stream %dth time! (buffer overflow will occur for 126th time)\n", rx_stream_reset_count);
                          rx_stream.reset();
                          rx_stream = usrp->get_rx_stream(stream_args);
                      }
                      auto_clear_freq_available = 0;
                    }
                    else {
                      rx_stream_error_count = 0;
                      auto_clear_freq_available = 1;
                    }
    
                    DEBUG_PRINT("READY_DATA state: %d, ant: %d, num_samples: %zu\n", state_vec[swing], antennaVector[0], nSamples_rx);
                    sock_send_int32(driverconn, state_vec[swing]);  // send status
                    sock_send_int32(driverconn, antennaVector[0]);   // send antenna TODO do this for both antennas?
                    sock_send_int32(driverconn, nSamples_rx);     // nsamples;  send send number of samples
                   
                    // read FAULT status   
                    bool fault;
                    for (iSide =0; iSide<nSides; iSide++){  
                        fault = read_FAULT_status_from_control_board(usrp, iSide);
                    }
                    // TODO move this in loop as soon as usrp_server receives both sides
                    sock_send_bool(driverconn, fault);     // FAULT status from conrol board
                
  
                    if (mute_output) {
                       DEBUG_PRINT("READY_DATA: Filling SHM with zeros (because of rx_worker error) \n");

                       for (iSide = 0; iSide<nSides; iSide++) {
                          memset(shm_rx_vec[iSide][swing],  0, rxshm_size);
                          std::fill(rx_auto_clear_freq[iSide].begin(), rx_auto_clear_freq[iSide].end(), 0);
                       }
                       mute_output = 0;
                    }
                    else {
                        DEBUG_PRINT("READY_DATA starting copying rx data buffer to shared memory\n");
                        // regural rx data
                        for (iSide = 0; iSide<nSides; iSide++) {
                            // DEBUG_PRINT("usrp_drivercopy to rx shm addr: %p iSide: %d iSwing: %d\n", shm_rx_vec[iSide][swing], iSide, iSwing);
                            memcpy(shm_rx_vec[iSide][swing], &rx_data_buffer[iSide][0], sizeof(std::complex<int16_t>) * nSamples_rx);
                        }
                        // auto clear freq samples
                        for (iSide = 0; iSide<nSides; iSide++) {
                            for (int iSample = 0; iSample < nSamples_auto_clear_freq; iSample++) {
                                rx_auto_clear_freq[iSide][iSample] = rx_data_buffer[iSide][nSamples_rx+nSamples_pause_after_rx+ iSample];
                            }
                        }
                    }

                    if(SAVE_RAW_SAMPLES_DEBUG) {
                        FILE *raw_dump_fp;
                        char raw_dump_name[80];
                        for (iSide=0; iSide<nSides; iSide++) {
                           sprintf(raw_dump_name,"%s/raw_samples_rx_ant_%d.cint16", diag_dir, antennaVector[iSide]);
                           raw_dump_fp = fopen(raw_dump_name, "wb");
                           fwrite(&rx_data_buffer[iSide], sizeof(std::complex<int16_t>), nSamples_rx_total, raw_dump_fp);
                           fclose(raw_dump_fp);
                        }

                    }

                    DEBUG_PRINT("READY_DATA finished copying rx data buffer to shared memory\n");
                    state_vec[swing] = ST_READY; 
                    DEBUG_PRINT("changing state_vec[swing] to ST_READY\n");

                    DEBUG_PRINT("READY_DATA returning command success \n");
                    sock_send_uint8(driverconn, READY_DATA);
                    break;
                    }

                case UHD_GETTIME: {
                    DEBUG_PRINT("entering UHD_GETTIME command\n");
                    start_time = usrp->get_time_now();

                    uint32_t real_time = start_time.get_real_secs();
                    double frac_time = start_time.get_frac_secs();

                    sock_send_uint32(driverconn, real_time);
                    sock_send_float64(driverconn, frac_time);

                    DEBUG_PRINT("UHD_GETTIME current UHD time: %d %.2f command\n", real_time, frac_time);
                    sock_send_uint8(driverconn, UHD_GETTIME);
                    break;
                    }
                // command to reset time, sync time with external PPS pulse
                case UHD_SYNC: {
                    DEBUG_PRINT("entering UHD_SYNC command\n");
                    // if --intclk flag passed to usrp_driver, set clock source as internal and do not sync time
                    if(al_intclk->count > 0) {
                        usrp->set_time_now(uhd::time_spec_t(0.0));
                    }

                    else {

                 /*       const uhd::time_spec_t last_pps_time = usrp->get_time_last_pps();
                        while (last_pps_time == usrp->get_time_last_pps()) {
                            boost::this_thread::sleep(boost::posix_time::milliseconds(100));
                        }
                        usrp->set_time_next_pps(uhd::time_spec_t(0.0));
                        boost::this_thread::sleep(boost::posix_time::milliseconds(1100));
                 */
                        DEBUG_PRINT("Start setting unknown pps\n");
                        usrp->set_time_unknown_pps(uhd::time_spec_t(11.0));
                        DEBUG_PRINT("end setting unknown pps\n");
                     }

                    sock_send_uint8(driverconn, UHD_SYNC);
                    break;
                    }

                case AUTOCLRFREQ: {
                    // has to be called after GET_DATA and before USRP_SETUP
                    DEBUG_PRINT("entering getting auto clear freq command\n");
//                    uint32_t num_clrfreq_samples = sock_get_uint32(driverconn);

                    iSide = 0;// TODO both sides!
                    if (auto_clear_freq_available) {
                        DEBUG_PRINT("AUTOCLRFREQ samples sending %d samples for antenna %d...\n", rx_auto_clear_freq[iSide].size(),antennaVector[iSide]);
                        sock_send_int32(driverconn, (int32_t) antennaVector[iSide]); 
                        sock_send_uint32(driverconn, (uint32_t) rx_auto_clear_freq[iSide].size());

                        // send samples                   
                        send(driverconn, &rx_auto_clear_freq[iSide][0], sizeof(std::complex<short int>) * rx_auto_clear_freq[iSide].size() , 0);
                    }
                    else {
                        sock_send_int32(driverconn, (int32_t) -1); 
                        
                    }

                    sock_send_uint8(driverconn, AUTOCLRFREQ);

                    break;

                    }
                case CLRFREQ: {
                    DEBUG_PRINT("entering CLRFREQ command\n");
                    uint32_t num_clrfreq_samples = sock_get_uint32(driverconn);
                    uint32_t clrfreq_time_full   = sock_get_uint32(driverconn);
                    double clrfreq_time_frac     = sock_get_float64(driverconn);
                    double clrfreq_cfreq         = sock_get_float64(driverconn);
                    double clrfreq_rate          = sock_get_float64(driverconn);

                    std::vector<std::vector<std::complex<int16_t>>> clrfreq_data_buffer(nSides, std::vector<std::complex<int16_t>>(num_clrfreq_samples));

                    uint32_t real_time; 
                    double frac_time;

                    DEBUG_PRINT("CLRFREQ time: %d . %.2f \n", clrfreq_time_full, clrfreq_time_frac);
                    DEBUG_PRINT("CLRFREQ rate: %.2f, CLRFREQ_nsamples %d, freq: %.2f\n", clrfreq_rate, num_clrfreq_samples, clrfreq_cfreq);
                    uhd::time_spec_t clrfreq_start_time = uhd::time_spec_t(clrfreq_time_full, clrfreq_time_frac);
                    real_time = clrfreq_start_time.get_real_secs();
                    frac_time = clrfreq_start_time.get_frac_secs();
                    DEBUG_PRINT("CLRFREQ UHD clrfreq target time: %d %.2f \n", real_time, frac_time);


                    // TODO: only set rate if it is different!
                    if(rxrate != clrfreq_rate) {
                       usrp->set_rx_rate(clrfreq_rate);
                       rxrate = usrp->get_rx_rate();
                       clrfreq_rate = rxrate;
                    }
                    DEBUG_PRINT("CLRFREQ actual rate: %.2f\n", clrfreq_rate);
                    //clrfreq_cfreq = usrp->get_rx_freq(); 
                    //DEBUG_PRINT("CLRFREQ actual freq: %.2f\n", clrfreq_cfreq);
                    clrfreq_threads.create_thread(boost::bind(usrp_rx_worker, usrp, rx_stream, &clrfreq_data_buffer, num_clrfreq_samples, clrfreq_start_time, &clrfreq_rx_worker_status));

                    clrfreq_threads.join_all();

                    if(clrfreq_rx_worker_status){
                        fprintf(stderr, "Error in clrfreq_rx_worker, resetting rx_stream: %d.\n", clrfreq_rx_worker_status);
                        rx_stream_reset_count++;
                        fprintf(stderr, "CLRFREQ: recreating rx_stream %dth time! (buffer overflow will occur for 126th time)\n", rx_stream_reset_count);
                        rx_stream.reset();
                        rx_stream = usrp->get_rx_stream(stream_args);
                    }

                    if (rx_stream_reset_count >= MAX_STREAM_RESETS) {
                        fprintf(stderr, "CLRFREQ: shutting down usrp_driver to avoid streamer reset overflow (after %dth reset)\n", rx_stream_reset_count);
                        // finish clrfreq command, then clean up and exit to avoid buffer overflow
                        exit_driver = 1;
                    }



                    DEBUG_PRINT("CLRFREQ received samples, relaying %d samples back...\n", num_clrfreq_samples);
                    sock_send_int32(driverconn, (int32_t) antennaVector[0]); // TODO both sides?
                    sock_send_float64(driverconn, clrfreq_rate);

                    // send back samples                   
                    send(driverconn, &clrfreq_data_buffer[0][0], sizeof(std::complex<short int>) * num_clrfreq_samples, 0);

                    //for(uint32_t i = 0; i < num_clrfreq_samples; i++) {
                        //DEBUG_PRINT("sending %d - %d\n", i, clrfreq_data_buffer[0][i]);
                    //    sock_send_cshort(driverconn, clrfreq_data_buffer[0][i]);
                   // }

                    DEBUG_PRINT("CLRFREQ samples sent for antenna %d...\n", antennaVector[0]);
                    // restore usrp rates
                    usrp->set_rx_rate(rxrate);
                    usrp->set_rx_freq(rxfreq);

                    sock_send_uint8(driverconn, CLRFREQ);
                    start_time = usrp->get_time_now();
                    real_time = start_time.get_real_secs();
                    frac_time = start_time.get_frac_secs();
                    DEBUG_PRINT("CLRFREQ finished at UHD time: %d %.2f \n", real_time, frac_time);

                    break;

                    }

                case EXIT: {
                    DEBUG_PRINT("entering EXIT command\n");

                    exit_driver = 1;
                    break;
                    }

                default: {
                    printf("USRP_DRIVER unrecognized command: %d, %c, exiting..\n", command, command);
                    sleep(10);
                    exit(1);
                    break;
                }
            }
            if (not check_clock_lock(usrp)) {
                fprintf(stderr,  "Error: Lost clock for USRP: %s\n ", as_host->sval[0]);
                exit_driver = 1; 
            }

            // clean exit
            if (exit_driver) {
                DEBUG_PRINT("Shutting down driver\n");
                close(driverconn);

                for(iSide = 0; iSide < nSides; iSide++) {
                    for(iSwing = 0; iSwing < nSwings; iSwing++) {
                        // fill SHM with zeros
                        memset(shm_rx_vec[iSide][iSwing], 0, rxshm_size);
                        memset(shm_tx_vec[iSide][iSwing], 0, txshm_size);

                        munmap(shm_rx_vec[iSide][iSwing], rxshm_size);
                        munmap(shm_tx_vec[iSide][iSwing], txshm_size);
                        sem_close(&sem_rx_vec[iSwing]);
                        sem_close(&sem_tx_vec[iSwing]);
                    }
                }
            
            // TODO: close usrp streams?
//            sock_send_uint8(driverconn, EXIT);
            exit(1);
          }

        }
    }
    
    return 0;
}
コード例 #19
0
ファイル: xyztk-rotate.c プロジェクト: steabert/xyztk
int main(int argc, char* argv[])
{
    struct arg_lit *help;
    struct arg_file *input, *output;
    struct arg_str *rotation;
    struct arg_end *end;

    /* command line parsing through argtable package */
    void* argtable[] = {
        help        = arg_lit0("h", "help", "display this help and exit"),
        input       = arg_file0("i", "input", "input", "name of the input file (default stdin"),
        output      = arg_file0("o", "output", "file", "name of the output file (default stdout)"),
        rotation    = arg_str1(NULL, NULL, "\"x y z w\"", "rotate w degrees around axis x y z"),
        end         = arg_end(20) };
    const char* progname = "xyztk-rotate";
    int rc = 0;
    int nerrors;

    /* verify the argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable) != 0)
        {
        /* NULL entries were detected, some allocations must have failed */
        printf("%s: insufficient memory\n", progname);
        rc=1;
        goto exit;
        }

    /* set default values */

    /* parse the command line flags, overriding default values */
    nerrors = arg_parse(argc,argv,argtable);

    /* special case: '--help' takes precedence over error reporting */
    if (help->count > 0)
        {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout,argtable,"\n");
        printf("\n");
        arg_print_glossary(stdout,argtable,"  %-40s %s\n");
        printf("\n");
        rc=0;
        goto exit;
        }

    /* special case: no command line options induces brief help */
    if (argc==1) {
        printf("Try '%s --help' for more information.\n",progname);
        rc=0;
        goto exit;
    }

    /* If the parser returned any errors then display them and exit */
    if (nerrors > 0)
        {
        /* Display the error details contained in the arg_end struct.*/
        arg_print_errors(stdout,end,progname);
        printf("Try '%s --help' for more information.\n",progname);
        rc=1;
        goto exit;
        }

    /* set global structures */

    /* initialize I/O pointers */
    FILE* in;
    if (input->count) {
      in = fopen(input->filename[0], "r");
    } else {
      in = stdin;
    }

    FILE* out;
    if (output->count) {
      out = fopen(output->filename[0], "w");
    } else {
      out = stdout;
    }

    /* initialize molecule structure */
    xyztk_molecule_t molecule;
    xyztk_molecule_load (&molecule, in);

    /* read rotation from string */
    xyztk_quat_t r;
    sscanf (rotation->sval[0], "%lf%lf%lf%lf", &r.x, &r.y, &r.z, &r.w);
    xyztk_molecule_rotate (&molecule, &r);

    /* print output */
    int i;
    fprintf(out, "%d\n", molecule.n_atoms);
    fprintf(out, "%s", molecule.name);
    for (i = 0; i < molecule.n_atoms; ++i)
      {
      fprintf(out, "%-8s %20.14lf %20.14lf %20.14lf \n",
	      molecule.label[i].s, molecule.coord[i].x, molecule.coord[i].y, molecule.coord[i].z);
      }

exit:
    /* deallocate each non-null entry in argtable[] */
    arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0]));

    return rc;
}
コード例 #20
0
ファイル: main.c プロジェクト: omf2097/openomf
int main(int argc, char* argv[]) {
    // commandline argument parser options
    struct arg_lit *help = arg_lit0("h", "help", "print this help and exit");
    struct arg_lit *vers = arg_lit0("v", "version", "print version information and exit");
    struct arg_file *file = arg_file1("f", "file", "<file>", "Input altpals file");
    struct arg_int *pal = arg_int1("p", "palette", "<number>", "Select a palette");
    struct arg_file *export = arg_file0("e", "export", "<file>", "Export selected palette to GPL file");
    struct arg_file *import = arg_file0("i", "import", "<file>", "Import selected palette from GPL file");
    struct arg_file *output = arg_file0("o", "output", "<file>", "Output altpals file");
    struct arg_end *end = arg_end(20);
    void* argtable[] = {help,vers,file,pal,output,import,export,end};
    const char* progname = "altpaltool";

    // Make sure everything got allocated
    if(arg_nullcheck(argtable) != 0) {
        printf("%s: insufficient memory\n", progname);
        goto exit_0;
    }

    // Parse arguments
    int nerrors = arg_parse(argc, argv, argtable);

    // Handle help
    if(help->count > 0) {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout, argtable, "\n");
        printf("\nArguments:\n");
        arg_print_glossary(stdout, argtable, "%-25s %s\n");
        goto exit_0;
    }

    // Handle version
    if(vers->count > 0) {
        printf("%s v0.1\n", progname);
        printf("Command line One Must Fall 2097 Altpals file editor.\n");
        printf("Source code is available at https://github.com/omf2097 under MIT license.\n");
        printf("(C) 2014 Tuomas Virtanen\n");
        goto exit_0;
    }

    // Handle errors
    if(nerrors > 0) {
        arg_print_errors(stdout, end, progname);
        printf("Try '%s --help' for more information.\n", progname);
        goto exit_0;
    }

    // Need import or export ...
    if(pal->count > 0 && import->count == 0 && export->count == 0) {
        printf("Define either --import or --export with --palette!\n");
        goto exit_0;
    }

    // Make sure output is set
    if(import->count > 0 && output->count <= 0) {
        printf("Define --output with --import.\n");
        goto exit_0;
    }

    // Load file
    sd_altpal_file alt;
    sd_altpal_create(&alt);
    int ret = sd_altpals_load(&alt, file->filename[0]);
    if(ret != SD_SUCCESS) {
        printf("Unable to load altpals file %s: %s.\n",
            file->filename[0],
            sd_get_error(ret));
        goto exit_1;
    }

    // Check ID
    int pal_id = pal->ival[0];
    if(pal_id < 0 || pal_id > SD_ALTPALS_PALETTES) {
        printf("Palette index %d does not exist!\n", pal_id);
        goto exit_1;
    }

    // Check what to do
    if(export->count > 0) {
        ret = sd_palette_to_gimp_palette(&alt.palettes[pal_id], export->filename[0]);
        if(ret == SD_SUCCESS) {
            printf("Palette %d exported to file %s succesfully.\n",
                pal_id,
                export->filename[0]);
        } else {
コード例 #21
0
ファイル: client.c プロジェクト: chiefdome/telex
int main(int argc, char *argv[])
{	
	struct arg_int *lport = arg_int0("p", "port", "<localport>",  "listening port (default is 8888)");
	struct arg_int *debug = arg_int0("d", "debug",  "<level>", "debug output level (default is 4)");	
#ifdef PUBKEY_DATA_
	struct arg_str *key   = arg_str0("k", "key",    "<keyfile>", "public key file (default is built-in)");
#else
	struct arg_str *key   = arg_str0("k", "key",    "<keyfile>", "public key file (default is pubkey)");
#endif
#ifdef ROOTPEM_DATA_
	struct arg_str *certdb= arg_str0(NULL, "certdb",    "<certfile>", "trusted CA database (default is built-in)");
#else
	struct arg_str *certdb= arg_str0(NULL, "certdb",    "<certfile>", "trusted CA database (default is root.pem)");
#endif
	struct arg_lit *help  = arg_lit0(NULL,"help",              "print this help and exit");
	struct arg_str *host  = arg_str1(NULL, NULL,    "<host>[:port]",  "non-blocked TLS server");
	struct arg_end *end   = arg_end(20);
	void *argtable[] = {lport, debug, key, certdb, help, host, end};
	const char* progname = "telex-client";
    int nerrors;
    int ret=0;
    assert(!arg_nullcheck(argtable));

	// defaults:
	lport->ival[0] = 8888;
	debug->ival[0] = 3;
#ifdef PUBKEY_DATA_
	key->sval[0] = NULL;
#else
	key->sval[0] = "pubkey";
#endif
#ifdef ROOTPEM_DATA_
	certdb->sval[0] = NULL;
#else
	certdb->sval[0] = "root.pem";
#endif

	nerrors = arg_parse(argc,argv,argtable);
    if (help->count > 0) {
		printf("Usage: %s", progname);
        arg_print_syntax(stdout,argtable,"\n");
        printf("\nEstablishes covert, encrypted tunnels, disguised as connections to <host>.\n\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
        printf("\n");		
		ret = 0;
	} else if (nerrors > 0) {
		arg_print_errors(stdout,end,progname);
		printf("Try '%s --help' for more information.\n", progname);
		ret = 1;
	} else if (argc == 1) {
        printf("Try '%s --help' for more information.\n", progname);
        ret = 0;
	} else {		

      int port = 443;
      char hstr[255];
      assert(host->sval[0]);
      strncpy(hstr, host->sval[0], sizeof(hstr)-1);

      char *pstr=0;
      strtok(hstr, ":");
      pstr = strtok(NULL, ":");
      if (pstr) {
	port = strtol(pstr, NULL, 10);
	if (port < 1 || port > 65535) {
	  fprintf(stderr, "Invalid remote port: %d", port);
	  return 1;
	}
      }

		printf("WARNING: This software is an experimental prototype intended for\n");
        printf("         researchers. It does not provide strong security and is\n");
        printf("         UNSAFE FOR REAL-WORLD USE. For details of current limitations\n");
        printf("         of our proof-of-concept, please see telex-client/ISSUES.\n");

      ret = telex_client(lport->ival[0], port, debug->ival[0], hstr, key->sval[0], certdb->sval[0]);
    }
    arg_freetable(argtable, sizeof(argtable)/sizeof(argtable[0]));
    return ret;
}
コード例 #22
0
ファイル: myprog.c プロジェクト: btbytes/examples
int main(int argc, char **argv)
    {
    struct arg_lit  *list    = arg_lit0("lL",NULL,                      "list files");
    struct arg_lit  *recurse = arg_lit0("R",NULL,                       "recurse through subdirectories");
    struct arg_int  *repeat  = arg_int0("k","scalar",NULL,              "define scalar value k (default is 3)");
    struct arg_str  *defines = arg_strn("D","define","MACRO",0,argc+2,  "macro definitions");
    struct arg_file *outfile = arg_file0("o",NULL,"<output>",           "output file (default is \"-\")");
    struct arg_lit  *verbose = arg_lit0("v","verbose,debug",            "verbose messages");
    struct arg_lit  *help    = arg_lit0(NULL,"help",                    "print this help and exit");
    struct arg_lit  *version = arg_lit0(NULL,"version",                 "print version information and exit");
    struct arg_file *infiles = arg_filen(NULL,NULL,NULL,1,argc+2,       "input file(s)");
    struct arg_end  *end     = arg_end(20);
    void* argtable[] = {list,recurse,repeat,defines,outfile,verbose,help,version,infiles,end};
    const char* progname = "myprog";
    int nerrors;
    int exitcode=0;

    /* verify the argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable) != 0)
        {
        /* NULL entries were detected, some allocations must have failed */
        printf("%s: insufficient memory\n",progname);
        exitcode=1;
        goto exit;
        }

    /* set any command line default values prior to parsing */
    repeat->ival[0]=3;
    outfile->filename[0]="-";

    /* Parse the command line as defined by argtable[] */
    nerrors = arg_parse(argc,argv,argtable);

    /* special case: '--help' takes precedence over error reporting */
    if (help->count > 0)
        {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout,argtable,"\n");
        printf("This program demonstrates the use of the argtable2 library\n");
        printf("for parsing command line arguments.\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
        exitcode=0;
        goto exit;
        }

    /* special case: '--version' takes precedence error reporting */
    if (version->count > 0)
        {
        printf("'%s' example program for the \"argtable\" command line argument parser.\n",progname);
        printf("September 2003, Stewart Heitmann\n");
        exitcode=0;
        goto exit;
        }

    /* If the parser returned any errors then display them and exit */
    if (nerrors > 0)
        {
        /* Display the error details contained in the arg_end struct.*/
        arg_print_errors(stdout,end,progname);
        printf("Try '%s --help' for more information.\n",progname);
        exitcode=1;
        goto exit;
        }

    /* special case: uname with no command line options induces brief help */
    if (argc==1)
        {
        printf("Try '%s --help' for more information.\n",progname);
        exitcode=0;
        goto exit;
        }

    /* normal case: take the command line options at face value */
    exitcode = mymain(list->count, recurse->count, repeat->ival[0],
                      defines->sval, defines->count,
                      outfile->filename[0], verbose->count,
                      infiles->filename, infiles->count);

    exit:
    /* deallocate each non-null entry in argtable[] */
    arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0]));

    return exitcode;
    }
コード例 #23
0
int main(int argc, char* argv[]) {

    double discountFactor;
    unsigned int maxNbEvaluations;
    char isTerminal = 0;
    char keepingTree = 0;
    int nbTimestep = -1;
    unsigned int branchingFactor = 0;

#ifdef USE_SDL
    char isDisplayed = 1;
    char isFullscreen = 1;
    char verbose = 0;
    char resolution[255] = "640x480";
#else
    char verbose = 1;
#endif

    uniform_instance* instance = NULL;

    state* crtState = NULL;
    state* nextState = NULL;
    double reward = 0.0;
    action* optimalAction = NULL;

    struct arg_dbl* g = arg_dbl1("g", "discountFactor", "<d>", "The discount factor for the problem");
    struct arg_int* n = arg_int1("n", "nbEvaluations", "<n>", "The number of evaluations");
    struct arg_int* s = arg_int0("s", "nbtimestep", "<n>", "The number of timestep");
    struct arg_int* b = arg_int0("b", "branchingFactor", "<n>", "The branching factor of the problem");
    struct arg_lit* k = arg_lit0("k", NULL, "Keep the subtree");
    struct arg_str* i = arg_str0(NULL, "state", "<s>", "The initial state to use");

#ifdef USE_SDL
    struct arg_lit* d = arg_lit0("d", NULL, "Display the viewer");
    struct arg_lit* f = arg_lit0("f", NULL, "Fullscreen");
    struct arg_lit* v = arg_lit0("v", NULL, "Verbose");
    struct arg_str* r = arg_str0(NULL, "resolution", "<s>", "The resolution of the display window");
    void* argtable[11];
    int nbArgs = 10;
#else
    void* argtable[7];
    int nbArgs = 6;
#endif

    struct arg_end* end = arg_end(nbArgs+1);
    int nerrors = 0;

    s->ival[0] = -1;
    b->ival[0] = 0;

    argtable[0] = g; argtable[1] = n; argtable[2] = s; argtable[3] = k; argtable[4] = b; argtable[5] = i;

#ifdef USE_SDL
    argtable[6] = d;
    argtable[7] = f;
    argtable[8] = v;
    argtable[9] = r;
#endif

    argtable[nbArgs] = end;

    if(arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        arg_freetable(argtable, nbArgs+1);
        return EXIT_FAILURE;
    }

    nerrors = arg_parse(argc, argv, argtable);

    if(nerrors > 0) {
        printf("%s:", argv[0]);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, argv[0]);
        arg_freetable(argtable, nbArgs+1);
        return EXIT_FAILURE;
    }

    discountFactor = g->dval[0];
    maxNbEvaluations = n->ival[0];

    branchingFactor = b->ival[0];

    initGenerativeModelParameters();
    if(branchingFactor)
        K = branchingFactor;
    initGenerativeModel();
    if(i->count)
        crtState = makeState(i->sval[0]);
    else
        crtState = initState();

#if USE_SDL
    isDisplayed = d->count;
    isFullscreen = f->count;
    verbose = v->count;
    if(r->count)
        strcpy(resolution, r->sval[0]);
#endif

    nbTimestep = s->ival[0];
    keepingTree = k->count;

    arg_freetable(argtable, nbArgs+1);

    instance = uniform_initInstance(crtState, discountFactor);

#ifdef USE_SDL
    if(isDisplayed) {
        if(initViewer(resolution, uniform_drawingProcedure, isFullscreen) == -1)
            return EXIT_FAILURE;
        viewer(crtState, NULL, 0.0, instance);
    }
#endif

    do {
        if(keepingTree)
            uniform_keepSubtree(instance);
        else
            uniform_resetInstance(instance, crtState);

        optimalAction = uniform_planning(instance, maxNbEvaluations);

        isTerminal = nextStateReward(crtState, optimalAction, &nextState, &reward);
        freeState(crtState);
        crtState = nextState;

        if(verbose) {
            printState(crtState);
            printAction(optimalAction);
            printf("reward: %f depth: %u\n", reward, uniform_getMaxDepth(instance));
        }

#ifdef USE_SDL
    } while(!isTerminal && (nbTimestep < 0 || --nbTimestep) && !viewer(crtState, optimalAction, reward, instance));
#else
    } while(!isTerminal && (nbTimestep < 0 || --nbTimestep));
コード例 #24
0
ファイル: main.c プロジェクト: omf2097/openomf
int main(int argc, char *argv[]) {
    SDL_AudioSpec want, have;
    SDL_AudioDeviceID dev;
    Streamer streamer;
    int retcode = 0;

    // Init SDL Audio
    if(SDL_Init(SDL_INIT_AUDIO) != 0) {
        fprintf(stderr, "Error: %s\n", SDL_GetError());
        return 1;
    }

    // commandline argument parser options
    struct arg_lit *help = arg_lit0("h", "help", "print this help and exit");
    struct arg_lit *vers = arg_lit0("v", "version", "print version information and exit");
    struct arg_file *file = arg_file1("f", "file", "<file>", "SOUNDS.DAT file");
    struct arg_file *output = arg_file0("o", "output", "<file>", "Output sounds file");
    struct arg_int *sid = arg_int0("s", "sound", "<int>", "Sound ID");
    struct arg_int *sampleprint = arg_int0(NULL, "print", "<int>", "Print first n bytes from selected sound");
    struct arg_lit *play = arg_lit0("p", "play", "Play selected sound");
    struct arg_file *export = arg_file0("e", "export", "<file>", "Export selected sound to AU file");
    struct arg_file *import = arg_file0("i", "import", "<file>", "Import selected sound from AU file");
    struct arg_end *end = arg_end(20);
    void* argtable[] = {help,vers,file,output,sid,sampleprint,play,export,import,end};
    const char* progname = "soundtool";

    // Make sure everything got allocated
    if(arg_nullcheck(argtable) != 0) {
        printf("%s: insufficient memory\n", progname);
        goto exit_0;
    }

    // Parse arguments
    int nerrors = arg_parse(argc, argv, argtable);

    // Handle help
    if(help->count > 0) {
        printf("Usage: %s", progname);
        arg_print_syntax(stdout, argtable, "\n");
        printf("\nArguments:\n");
        arg_print_glossary(stdout, argtable, "%-25s %s\n");
        goto exit_0;
    }

    // Handle version
    if(vers->count > 0) {
        printf("%s v0.1\n", progname);
        printf("Command line One Must Fall 2097 SOUNDS.DAT file editor.\n");
        printf("Source code is available at https://github.com/omf2097 under MIT license.\n");
        printf("(C) 2013 Tuomas Virtanen\n");
        goto exit_0;
    }

    // Handle errors
    if(nerrors > 0) {
        arg_print_errors(stdout, end, progname);
        printf("Try '%s --help' for more information.\n", progname);
        goto exit_0;
    }

    // Open sounds.dat
    sd_sound_file sf;
    sd_sounds_create(&sf);
    retcode = sd_sounds_load(&sf, file->filename[0]);
    if(retcode) {
        printf("Error %d: %s\n", retcode, sd_get_error(retcode));
        goto exit_1;
    }

    if(sid->count > 0) {
        // Sound ID to handle
        int sound_id = sid->ival[0];
        const sd_sound *sound = sd_sounds_get(&sf, sound_id-1);
        if(sound == NULL) {
            printf("Invalid sound ID");
            goto exit_1;
        }

        if(sampleprint->count > 0) {
            int count = (sampleprint->ival[0] > sound->len) ? sound->len : sampleprint->ival[0];
            printf("Sample size = %d\n", sound->len);
            printf("Unknown = %d\n", sound->unknown);
            printf("Attempting to print %d first bytes.\n", count);
            for(int i = 0; i < count; i++) {
                unsigned int s = sound->data[i] & 0xFF;
                printf("%2x ", s);
            }
        } else if(play->count > 0) {
            printf("Attempting to play sample #%d.\n", sound_id);

            // Make sure there is data at requested ID position
            if(sound->len <= 0) {
                printf("Sample does not contain data.\n");
                goto exit_1;
            }

            // Streamer
            streamer.size = sound->len;
            streamer.pos = 0;
            streamer.data = sound->data;

            // Initialize required audio
            SDL_zero(want);
            want.freq = 8000;
            want.format = AUDIO_U8;
            want.channels = 1;
            want.samples = 4096;
            want.callback = stream;
            want.userdata = &streamer;

            // Open device, play file
            dev = SDL_OpenAudioDevice(NULL, 0, &want, &have, 0);
            if(dev == 0) {
                printf("Failed to open audio dev: %s\n", SDL_GetError());
                goto exit_0;
            } else {
                if(have.format != want.format) {
                    printf("Could not get correct playback format.\n");
                } else {
                    printf("Starting playback ...\n");
                    SDL_PauseAudioDevice(dev, 0);
                    while(streamer.pos < streamer.size) {
                        SDL_Delay(100);
                    }
                    printf("All done.\n");
                }
                SDL_CloseAudioDevice(dev);
            }
        } else if(import->count > 0) {
            if(sd_sound_from_au(&sf, sound_id, import->filename[0]) != SD_SUCCESS) {
                printf("Importing sample %d from file %s failed.\n", sound_id, import->filename[0]);
            } else {
                printf("Importing sample %d from file %s succeeded.\n", sound_id, import->filename[0]);
            }
        } else if(export->count > 0) {
            if(sd_sound_to_au(&sf, sound_id, export->filename[0]) != SD_SUCCESS) {
                printf("Exporting sample %d to file %s failed.\n", sound_id, export->filename[0]);
            } else {
                printf("Exporting sample %d to file %s succeeded.\n", sound_id, export->filename[0]);
            }
        } else {
コード例 #25
0
ファイル: main.c プロジェクト: hikinggrass/eiwomisarc_server
int main(int argc, char **argv)
{
	struct arg_int *serverport = arg_int0("pP","port","","serverport, default: 1337");
	struct arg_str *serialport = arg_str0("sS", "serial", "", "serial port, default /dev/ttyS0");

	struct arg_int *baud = arg_int0("bB", "baud","","baudrate, default: 9600");
	
	struct arg_str *client = arg_str0("cC","client","","only accept messages from this client");

    struct arg_lit  *help    = arg_lit0("hH","help","print this help and exit");
    struct arg_lit  *version = arg_lit0(NULL,"version","print version information and exit");

	struct arg_lit  *debug = arg_lit0(NULL,"debug","print debug messages");
    struct arg_lit  *silent = arg_lit0(NULL,"silent","print no messages");

    struct arg_end  *end     = arg_end(20);

    void* argtable[] = {serverport,serialport,baud,client,help,version,debug,silent,end};

    int nerrors;
    int exitcode=0;

    /* verify the argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable) != 0) {
        /* NULL entries were detected, some allocations must have failed */
        printf("%s: insufficient memory\n",PROGNAME);
        exitcode=1;
        goto exit;
	}

    /* set any command line default values prior to parsing */
	/* nothing */

    /* Parse the command line as defined by argtable[] */
    nerrors = arg_parse(argc,argv,argtable);

    /* special case: '--help' takes precedence over error reporting */
    if (help->count > 0) {
		printf("usage: %s", PROGNAME);
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
        exitcode=0;
        goto exit;
	}

    /* special case: '--version' takes precedence error reporting */
    if (version->count > 0) {
        printf("'%s' version ",PROGNAME);
		printf("%s",VERSION);
		printf("\nGIT-REVISION: ");
		printf("%s",GITREV);
        printf("\n%s receives udp-packets and controls\n",PROGNAME);
		printf("the EIWOMISA controller over RS-232\n");
        printf("%s",COPYRIGHT);
		printf("\n");
        exitcode=0;
        goto exit;
	}

    /* If the parser returned any errors then display them and exit */
    if (nerrors > 0) {
        /* Display the error details contained in the arg_end struct.*/
        arg_print_errors(stdout,end,PROGNAME);
        printf("Try '%s --help' for more information.\n",PROGNAME);
        exitcode=1;
        goto exit;
	}

    /* special case: with no command line options induce brief help and use defaults */
    if (argc==1) {
		printf("No command-line options present, using defaults.\n",PROGNAME);
        printf("Try '%s --help' for more information.\n",PROGNAME);
	}

    /* normal case: take the command line options at face value */

	/* check if server port is set */
	int i_serverport = -1;
	if(serverport->count>0)
		i_serverport = (int)serverport->ival[0];

	/* check if serial port is set */
	char* i_serialport = NULL;
	if(serialport->count>0)
		i_serialport = (char*)serialport->sval[0];

	/* check if baudrate is set */
	int i_baudrate = -1;
	if(baud->count>0)
		i_baudrate = (int)baud->ival[0];
	
	/* check if client ip is set */
	char* i_client = NULL;
	if(client->count>0) {
		i_client = (char *)client->sval[0];
	}
	
	/* --debug enables debug messages */
    if (debug->count > 0) {
		printf("debug messages enabled\n");
		msglevel = 3;
	}

	/* --silent disables all (!) messages */
    if (silent->count > 0) {
		msglevel = 0;
	}

	exitcode = mymain(i_serverport, i_serialport, i_baudrate, i_client);

exit:
    /* deallocate each non-null entry in argtable[] */
    arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0]));

    return exitcode;
}
コード例 #26
0
int main(int argc, char* argv[]) {

#ifdef BALL
    double discountFactor = 0.9;
#else
#ifdef CART_POLE
    double discountFactor = 0.95;
#else
#ifdef DOUBLE_CART_POLE
    double discountFactor = 0.95;
#else
#ifdef MOUNTAIN_CAR
    double discountFactor = 0.99;
#else
#ifdef ACROBOT
    double discountFactor = 0.95;
#else
#ifdef BOAT
    double discountFactor = 0.95;
#else
#ifdef CART_POLE_BINARY
    double discountFactor = 0.95;
#else
#ifdef SWIMMER
    double discountFactor = 0.95;
#endif
#endif
#endif
#endif
#endif
#endif
#endif
#endif

    FILE* initFileFd = NULL;
    state** initialStates = NULL;
    FILE* results = NULL;
    char str[1024];
    unsigned int i = 0;
    unsigned int h = 0;
    unsigned int* ns = NULL;
    unsigned int nbN = 0;
    unsigned int n = 0;
    unsigned int nbSteps = 0;
    unsigned int timestamp = time(NULL);
    int readFscanf = -1;

    optimistic_instance* optimistic = NULL;

    struct arg_file* initFile = arg_file1(NULL, "init", "<file>", "File containing the inital state");
    struct arg_str* r = arg_str1("n", NULL, "<s>", "List of maximum numbers of evaluations");
    struct arg_int* s = arg_int1("s", NULL, "<n>", "Number of steps");
    struct arg_int* k = arg_int1("k", NULL, "<n>", "Branching factor of the problem");
    struct arg_file* where = arg_file1(NULL, "where", "<file>", "Directory where we save the outputs");
    struct arg_end* end = arg_end(6);

    int nerrors = 0;
    void* argtable[6];

    argtable[0] = initFile;
    argtable[1] = r;
    argtable[2] = s;
    argtable[3] = k;
    argtable[4] = where;
    argtable[5] = end;

    if(arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        arg_freetable(argtable, 6);
        return EXIT_FAILURE;
    }

    nerrors = arg_parse(argc, argv, argtable);

    if(nerrors > 0) {
        printf("%s:", argv[0]);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, argv[0]);
        arg_freetable(argtable, 6);
        return EXIT_FAILURE;
    }

    initGenerativeModelParameters();
    K = k->ival[0];
    initGenerativeModel();

    initFileFd = fopen(initFile->filename[0], "r");
    readFscanf = fscanf(initFileFd, "%u\n", &n);
    initialStates = (state**)malloc(sizeof(state*) * n);
    
    for(; i < n; i++) {
        readFscanf = fscanf(initFileFd, "%s\n", str);
        initialStates[i] = makeState(str);
    }
    fclose(initFileFd);

    nbSteps = s->ival[0];
    ns = parseUnsignedIntList((char*)r->sval[0], &nbN);

    optimistic = optimistic_initInstance(NULL, discountFactor);

    sprintf(str, "%s/%u_results_%u_%u.csv", where->filename[0], timestamp, K, nbSteps);
    results = fopen(str, "w");

    for(h = 0; h < nbN; h++) {
        double sumRewards = 0.0;

        for(i = 0; i < n; i++) {
            unsigned int j = 0;
            state* crt = copyState(initialStates[i]);

            optimistic_resetInstance(optimistic, crt);
            for(; j < nbSteps; j++) {
                char isTerminal = 0;
                double reward = 0.0;
                state* nextState = NULL;

                optimistic_keepSubtree(optimistic);
                action* optimalAction = optimistic_planning(optimistic, ns[h]);
                isTerminal = nextStateReward(crt, optimalAction, &nextState, &reward) < 0 ? 1 : 0;
                freeState(crt);
                crt = nextState;
                sumRewards += reward;
                if(isTerminal)
                    break;
            }
            optimistic_resetInstance(optimistic, crt);
            freeState(crt);

            printf(">>>>>>>>>>>>>> %uth initial state processed\n", i + 1);
            fflush(NULL);
        }

        fprintf(results, "%u,%.15f\n", ns[h], sumRewards / (double)n);
        printf(">>>>>>>>>>>>>> n = %u  done\n\n", ns[h]);
        fflush(NULL);
    }

    fclose(results);

    arg_freetable(argtable, 6);

    for(i = 0; i < n; i++)
        freeState(initialStates[i]);

    free(initialStates);

    optimistic_uninitInstance(&optimistic);

    freeGenerativeModel();
    freeGenerativeModelParameters();

    return EXIT_SUCCESS;

}
コード例 #27
0
ファイル: Main.cpp プロジェクト: tyrel/DCPUToolchain
int main(int argc, char* argv[])
{
	// Define arguments.
	struct arg_lit* show_help = arg_lit0("h", "help", "Show this help.");
	struct arg_str* type_assembler = arg_str0("t", NULL, "<type>", "The type of assembler to output for.");
	struct arg_file* input_file = arg_file1(NULL, NULL, "<file>", "The input file (or - to read from standard input).");
	struct arg_file* output_file = arg_file1("o", "output", "<file>", "The output file (or - to send to standard output).");
	struct arg_end *end = arg_end(20);
	void *argtable[] = { output_file, show_help, type_assembler, input_file, end };

	// Parse arguments.
	int nerrors = arg_parse(argc,argv,argtable);
	if (nerrors != 0 || show_help->count != 0)
	{
		if (show_help->count != 0)
			arg_print_errors(stdout, end, "compiler");
		fprintf(stderr, "syntax:\n    compiler");
		arg_print_syntax(stdout, argtable, "\n");
		fprintf(stderr, "options:\n");
		arg_print_glossary(stdout, argtable, "    %-25s %s\n");
		return 1;
	}

	// Parse C.
	pp_add_search_path(".");
	pp_add_search_path("include");
	pp_add_search_path(dirname<std::string>(input_file->filename[0]).c_str());
	yyout = stderr;
	yyin = pp_do(input_file->filename[0]);
	if (yyin == NULL)
	{
		pp_cleanup();
		return 1;
	}
	yyparse();
	if (yyin != stdin)
		fclose(yyin);
	pp_cleanup();
	if (program == NULL)
	{
		std::cerr << "An error occurred while compiling." << std::endl;
		return 1;
	}

	// Assembler type.
	const char* asmtype = "dcpu16toolchain";
	if (type_assembler->count > 0)
		asmtype = type_assembler->sval[0];

	// Spacing.
	std::cerr << std::endl;

	// Generate assembly using the AST.
	try
	{
		AsmGenerator generator(asmtype);
		AsmBlock* block = program->compile(generator);
		if (strcmp(output_file->filename[0], "-") == 0)
		{
			std::cout << generator.m_Preassembly << std::endl;
			std::cout << *block << std::endl;
			std::cout << generator.m_Postassembly << std::endl;
		}
		else
		{
			std::ofstream output(output_file->filename[0], std::ios::out | std::ios::trunc);
			output << generator.m_Preassembly << std::endl;
			output << *block << std::endl;
			output << generator.m_Postassembly << std::endl;
			output.close();
		}
		delete block;
	}
	catch (CompilerException* ex)
	{
		std::string msg = ex->getMessage();
		std::cerr << "An error occurred while compiling." << std::endl;
		std::cerr << msg << std::endl;
		return 1;
	}
	
	return 0;
}
コード例 #28
0
ファイル: test_dbl.c プロジェクト: Debug-Orz/sploit-dev
int main(int argc, char **argv)
    {
    struct arg_dbl *a    = arg_dbl1(NULL,NULL,"a","a is <double>");
    struct arg_dbl *b    = arg_dbl0(NULL,NULL,"b","b is <double>");
    struct arg_dbl *c    = arg_dbl0(NULL,NULL,"c","c is <double>");
    struct arg_dbl *d    = arg_dbln("dD","delta","<double>",0,3,"d can occur 0..3 times");
    struct arg_dbl *e    = arg_dbl0(NULL,"eps,eqn","<double>","eps is optional");
    struct arg_lit *help = arg_lit0(NULL,"help","print this help and exit");
    struct arg_end *end  = arg_end(20);
    void* argtable[] = {a,b,c,d,e,help,end};
    int nerrors;
    int exitcode=0;
    int i;
    double sum=0;
    
    /*
    printf("a=%p\n",a);
    printf("b=%p\n",b);
    printf("c=%p\n",c);
    printf("d=%p\n",d);
    printf("e=%p\n",e);
    printf("help=%p\n",help);
    printf("end=%p\n",end);
    printf("argtable=%p\n",argtable);
    */
    
    /* print the command line */
    for (i=0; i<argc; i++)
        printf("%s ",argv[i]);
    printf("\n");
    
    /* verify the argtable[] entries were allocated sucessfully */
    if (arg_nullcheck(argtable) != 0)
        {
        /* NULL entries were detected, some allocations must have failed */
        printf("%s: insufficient memory\n",argv[0]);
        exitcode=1;
        goto exit;
        }
    
    /* Parse the command line as defined by argtable[] */
    nerrors = arg_parse(argc,argv,argtable);

    /* special case: '--help' takes precedence over error reporting */
    if (help->count > 0)
        {
        printf("Usage: %s ", argv[0]);
        arg_print_syntax(stdout,argtable,"\n");
        arg_print_glossary(stdout,argtable,"  %-25s %s\n");
        exitcode=0;
        goto exit;
        }

    /* If the parser returned any errors then display them and exit */
    if (nerrors > 0)
        {
        /* Display the error details contained in the arg_end struct.*/
        arg_print_errors(stdout,end,argv[0]);
        exitcode=1;
        goto exit;
        }

    /* parsing complete, verify all args sum to zero */
    for (i=0; i<a->count; i++)
        {
        printf("a[%d]=%f\n",i,a->dval[i]);
        sum += a->dval[i];
        }
    for (i=0; i<b->count; i++)
        {
        printf("b[%d]=%f\n",i,b->dval[i]);
        sum += b->dval[i];
        }
    for (i=0; i<c->count; i++)
        {
        printf("c[%d]=%f\n",i,c->dval[i]);
        sum += c->dval[i];
        }
    for (i=0; i<d->count; i++)
        {
        printf("d[%d]=%f\n",i,d->dval[i]);
        sum += d->dval[i];
        }
    for (i=0; i<e->count; i++)
        {
        printf("e[%d]=%f\n",i,e->dval[i]);
        sum += e->dval[i];
        }
    printf("sum=%f\n",sum);
    if (sum<-1.0e-6 || sum>1.0e-6)
        {
        printf("%s: error - sum=%f is non-zero\n",argv[0],sum);
        exitcode=1;
        goto exit;
        }
        
    exit:
    /* deallocate each non-null entry in argtable[] */
    arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0]));
    
    printf("%s: exitcode=%d\n\n",argv[0],exitcode);

    /* close stdin and stdout to stop memcheck whining about their memory not being freed */
    fclose(stdin);
    fclose(stdout);
   
    return exitcode;
    }
int main(int argc, char* argv[]) {

#ifdef BALL
    double discountFactor = 0.9;
#else
#ifdef CART_POLE
    double discountFactor = 0.95;
#else
#ifdef DOUBLE_CART_POLE
    double discountFactor = 0.95;
#else
#ifdef MOUNTAIN_CAR
    double discountFactor = 0.99;
#else
#ifdef ACROBOT
    double discountFactor = 0.95;
#else
#ifdef BOAT
    double discountFactor = 0.95;
#else
#ifdef SWIMMER
    double discountFactor = 0.95;
#endif
#endif
#endif
#endif
#endif
#endif
#endif

    FILE* initFileFd = NULL;
    state** initialStates = NULL;
    FILE* results = NULL;
    char str[1024];
    unsigned int i = 0;
    unsigned int nbInitialStates = 0;
    unsigned int* ns = NULL;
    unsigned int nbN = 0;
    double* Ls = NULL;
    unsigned int nbL = 0;
    unsigned int nbSteps = 0;
    unsigned int timestamp = time(NULL);
    int readFscanf = -1;

    lipschitzian_instance* lipschitzian = NULL;

    struct arg_file* initFile = arg_file1(NULL, "init", "<file>", "File containing the inital state");
    struct arg_int* s = arg_int1("s", NULL, "<n>", "Number of steps");
    struct arg_str* r = arg_str1("n", NULL, "<s>", "List of ressources");
    struct arg_str* z = arg_str1("L", NULL, "<s>", "List of Lipschitz coefficients to try");
    struct arg_file* where = arg_file1(NULL, "where", "<file>", "Directory where we save the outputs");
    struct arg_end* end = arg_end(6);

    int nerrors = 0;
    void* argtable[6];

    argtable[0] = initFile;
    argtable[1] = r;
    argtable[2] = s;
    argtable[3] = z;
    argtable[4] = where;
    argtable[5] = end;

    if(arg_nullcheck(argtable) != 0) {
        printf("error: insufficient memory\n");
        arg_freetable(argtable, 6);
        return EXIT_FAILURE;
    }

    nerrors = arg_parse(argc, argv, argtable);

    if(nerrors > 0) {
        printf("%s:", argv[0]);
        arg_print_syntax(stdout, argtable, "\n");
        arg_print_errors(stdout, end, argv[0]);
        arg_freetable(argtable, 6);
        return EXIT_FAILURE;
    }

    initGenerativeModelParameters();
    initGenerativeModel();

    initFileFd = fopen(initFile->filename[0], "r");
    readFscanf = fscanf(initFileFd, "%u\n", &nbInitialStates);
    initialStates = (state**)malloc(sizeof(state*) * nbInitialStates);
    
    for(; i < nbInitialStates; i++) {
        readFscanf = fscanf(initFileFd, "%s\n", str);
        initialStates[i] = makeState(str);
    }
    fclose(initFileFd);

    nbSteps = s->ival[0];
    Ls = parseDoubleList((char*)z->sval[0], &nbL);
    ns = parseUnsignedIntList((char*)r->sval[0], &nbN);

    sprintf(str, "%s/%u_results_%s_%s.csv", where->filename[0], timestamp, z->sval[0], r->sval[0]);
    results = fopen(str, "w");

    lipschitzian = lipschitzian_initInstance(NULL, discountFactor, 0.0);
    
    for(i = 0; i < nbN; i++) {                                               /* Loop on the computational ressources */
        fprintf(results, "%u", ns[i]);
        printf("Starting with %u computational ressources\n", ns[i]);
        fflush(NULL);
        unsigned int j = 0;
        for(; j < nbL; j++) {                                           /* Loop on the Lispchitz constant */
            unsigned int k = 0;
            double average = 0.0;
            lipschitzian->L = Ls[j];
            for(; k < nbInitialStates; k++) {                           /* Loop on the initial states */
                unsigned int l = 0;
                double sumRewards = 0.0;
                state* crt = copyState(initialStates[k]);

                lipschitzian_resetInstance(lipschitzian, crt);
                for(; l < nbSteps; l++) {                               /* Loop on the step */
                    char isTerminal = 0;
                    double reward = 0.0;
                    state* nextState = NULL;

                    double* optimalAction = lipschitzian_planning(lipschitzian, ns[i]);
                    isTerminal = nextStateReward(crt, optimalAction, &nextState, &reward) < 0 ? 1 : 0;
                    free(optimalAction);
                    freeState(crt);
                    crt = nextState;
                    sumRewards += reward;
                    lipschitzian_resetInstance(lipschitzian,crt);
                    if(isTerminal)
                        break;
                }
                average += sumRewards;
                freeState(crt);
                printf("Computation of the %u initial state done with L=%f\n", k, Ls[j]);
                fflush(NULL);
            }
            average = average /(double)nbInitialStates;
            fprintf(results, ",%.15f", average);
            printf("Computation with L=%f and n=%u done\n", Ls[j], ns[i]);
            fflush(NULL);
        }
        fprintf(results,"\n");
        printf("Computation with %u computational ressources done\n\n", ns[i]);
        fflush(NULL);
    }

    fclose(results);

    arg_freetable(argtable, 6);

    for(i = 0; i < nbInitialStates; i++)
        freeState(initialStates[i]);

    free(initialStates);

    lipschitzian_uninitInstance(&lipschitzian);

    free(ns);
    free(Ls);

    freeGenerativeModel();
    freeGenerativeModelParameters();

    return EXIT_SUCCESS;

}
コード例 #30
0
ファイル: main.cpp プロジェクト: andre-d/DCPUToolchain
int main(int argc, char* argv[])
{
	// Define arguments.
	struct arg_lit* show_help = arg_lit0("h", "help", "Show this help.");
	struct arg_str* type_assembler = arg_str0("t", NULL, "<type>", "The type of assembler to output for.");
	struct arg_file* input_file = arg_file1(NULL, NULL, "<file>", "The input file (or - to read from standard input).");
	struct arg_file* output_file = arg_file1("o", "output", "<file>", "The output file (or - to send to standard output).");
	// 20 is maxcount for include directories, this has to be set to some constant number.
	struct arg_file* include_dirs = arg_filen("I", NULL, "<directory>", 0, 20, "Adds the directory <dir> to the directories to be searched for header files.");
	struct arg_lit* verbose = arg_litn("v", NULL, 0, LEVEL_EVERYTHING - LEVEL_DEFAULT, "Increase verbosity.");
	struct arg_lit* quiet = arg_litn("q", NULL,  0, LEVEL_DEFAULT - LEVEL_SILENT, "Decrease verbosity.");
	struct arg_end* end = arg_end(20);
	void* argtable[] = { output_file, show_help, type_assembler, include_dirs, input_file, verbose, quiet, end };

	// Parse arguments.
	int nerrors = arg_parse(argc, argv, argtable);

	version_print(bautofree(bfromcstr("Compiler")));
	if (nerrors != 0 || show_help->count != 0)
	{
		if (nerrors != 0)
			arg_print_errors(stderr, end, "compiler");

		fprintf(stderr, "syntax:\n    dtcc");
		arg_print_syntax(stderr, argtable, "\n");
		fprintf(stderr, "options:\n");
		arg_print_glossary(stderr, argtable, "	  %-25s %s\n");
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	// Set verbosity level.
	debug_setlevel(LEVEL_DEFAULT + verbose->count - quiet->count);

	// Set global path variable.
	osutil_setarg0(bautofree(bfromcstr(argv[0])));

	// Run the preprocessor.
	ppfind_add_path(bautofree(bfromcstr(".")));
	ppfind_add_path(bautofree(bfromcstr("include")));
	ppfind_add_autopath(bautofree(bfromcstr(input_file->filename[0])));
	for (int i = 0; i < include_dirs->count; ++i)
		ppfind_add_path(bautofree(bfromcstr(include_dirs->filename[i])));
	bstring pp_result_name = pp_do(bautofree(bfromcstr(input_file->filename[0])));

	if (pp_result_name == NULL)
	{
		fprintf(stderr, "compiler: invalid result returned from preprocessor.\n");
		pp_cleanup(bautofree(pp_result_name));
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	// Parse C.
	yyout = stderr;
	yyin = fopen((const char*)(pp_result_name->data), "r");

	if (yyin == NULL)
	{
		pp_cleanup(bautofree(pp_result_name));
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	yyparse();

	if (yyin != stdin)
		fclose(yyin);

	pp_cleanup(bautofree(pp_result_name));

	if (program == NULL)
	{
		std::cerr << "An error occurred while compiling." << std::endl;
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	// Assembler type.
	const char* asmtype = "toolchain";

	if (type_assembler->count > 0)
		asmtype = type_assembler->sval[0];

	// Initially save to a temporary file.
	std::string temp = std::string(tempnam(".", "cc."));

	// Generate assembly using the AST.
	try
	{
		AsmGenerator generator(asmtype);
		AsmBlock* block = program->compile(generator);

		std::ofstream output(temp.c_str(), std::ios::out | std::ios::trunc);
		if (output.bad() || output.fail())
		{
			printd(LEVEL_ERROR, "compiler: temporary file not writable.\n");
			arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
			return 1;
		}
		output << *block << std::endl;
		output.close();

		delete block;
	}
	catch (CompilerException* ex)
	{
		std::string msg = ex->getMessage();
		std::cerr << "An error occurred while compiling." << std::endl;
		std::cerr << msg << std::endl;
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	// Re-open the temporary file for reading.
	std::ifstream input(temp.c_str(), std::ios::in);
	if (input.bad() || input.fail())
	{
		printd(LEVEL_ERROR, "compiler: temporary file not readable.\n");
		arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
		return 1;
	}

	// Open the output file.
	std::ostream* output;
	if (strcmp(output_file->filename[0], "-") != 0)
	{
		// Write to file.
		output = new std::ofstream(output_file->filename[0], std::ios::out | std::ios::trunc);

		if (output->bad() || output->fail())
		{
			printd(LEVEL_ERROR, "compiler: output file not readable.\n");
			arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
			return 1;
		}
	}
	else
	{
		// Set output to cout.
		output = &std::cout;
	}

	// Copy data.
	std::copy(std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>(), std::ostreambuf_iterator<char>(*output));

	// Close files and delete temporary.
	if (strcmp(output_file->filename[0], "-") != 0)
	{
		((std::ofstream*)output)->close();
		delete output;
	}
	input.close();
	unlink(temp.c_str());

	arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0]));
	return 0;
}