예제 #1
0
파일: mconfig.c 프로젝트: MLDroid/malheur
/**
 * Checks if the configuration is valid. The function checks if all 
 * required parameters are set and adds default values if necessary.
 * @param cfg configuration
 */
void config_check(config_t *cfg)
{
    int i, j;
    const char *s;
    double f;
    config_setting_t *cs, *vs;

    for (i = 0; defaults[i].name; i++) {
        /* Lookup setting group */
        cs = config_lookup(cfg, defaults[i].group);
        if (!cs)
            cs = config_setting_add(config_root_setting(cfg),
                                    defaults[i].group, CONFIG_TYPE_GROUP);

        /* (1) Check for string */
        if (defaults[i].type == CONFIG_TYPE_STRING) {
            if (config_setting_lookup_string(cs, defaults[i].name, &s))
                continue;

            /* Add default value */
            vs = config_setting_add(cs, defaults[i].name, CONFIG_TYPE_STRING);
            config_setting_set_string(vs, defaults[i].val.sval);
        /* (2) Check for float */            
        } else if (defaults[i].type == CONFIG_TYPE_FLOAT) {
            if (config_setting_lookup_float(cs, defaults[i].name, &f))
                continue;

            /* Check for mis-interpreted integer */
            if (config_setting_lookup_int(cs, defaults[i].name, &j)) {
                config_setting_remove(cs, defaults[i].name);
                vs = config_setting_add(cs, defaults[i].name, CONFIG_TYPE_FLOAT);
                config_setting_set_float(vs, (double) j);
                continue;
            }

            /* Add default value */
            vs = config_setting_add(cs, defaults[i].name, CONFIG_TYPE_FLOAT);
            config_setting_set_float(vs, defaults[i].val.fval);
        /* (3) Check for integer */            
        } else if (defaults[i].type == CONFIG_TYPE_INT) {
            if (config_setting_lookup_int(cs, defaults[i].name, &j))
                continue;

            /* Check for mis-interpreted float */
            if (config_setting_lookup_float(cs, defaults[i].name, &f)) {
                config_setting_remove(cs, defaults[i].name);
                vs = config_setting_add(cs, defaults[i].name, CONFIG_TYPE_INT);
                config_setting_set_int(vs, (long) round(f));
                continue;
            }

            /* Add default value */
            vs = config_setting_add(cs, defaults[i].name, CONFIG_TYPE_INT);
            config_setting_set_int(vs, defaults[i].val.ival);
        } else {
            error("Unknown configuration type");
        }
    }
}
예제 #2
0
int get_layout(struct layout_t* out, int num_frame, int id_layout)
{
	config_setting_t *category_list, *category, *layout_list, *layout, *frame_list, *frame;
	config_setting_t *pos, *size;
	config_t layout_config;
	int frame_length, i;

	out->num_frames = num_frame;
	out->perc_to_pixel = 0; 
	out->frames = (struct frame_t*) malloc (num_frame * sizeof(struct frame_t));

	config_init(&layout_config);
	config_read_file(&layout_config, "./layout.cfg");
	
	category_list = config_lookup(&layout_config, "application.layout_group");
	category = config_setting_get_elem(category_list, num_frame - MIN_NUM_FRAME);
	
	layout_list = config_setting_get_member(category, "layout");
	layout = config_setting_get_elem(layout_list, id_layout);

	frame_list = config_setting_get_member(layout, "frame");
	frame_length = config_setting_length(frame_list);
	for(i = 0; i < frame_length; i++)
	{
		frame = config_setting_get_elem(frame_list, i);
		pos= config_setting_get_member(frame, "pos");
		size = config_setting_get_member(frame, "size");
		if (config_setting_lookup_float(pos, "x", &(out->frames[i].pos_x))==CONFIG_FALSE)
			printf("pos.x:\tONFIG_FALSE\n");

if ( config_setting_lookup_float(pos, "y", &(out->frames[i].pos_y))==CONFIG_FALSE)
			printf("pos.y:\tONFIG_FALSE\n");
		
if ( config_setting_lookup_float(size, "w", &(out->frames[i].width))==CONFIG_FALSE)
			printf("size.w:\tONFIG_FALSE\n");

if ( config_setting_lookup_float(size, "h", &(out->frames[i].height))==CONFIG_FALSE)
			printf("size.h:\tONFIG_FALSE\n");

		
		config_setting_lookup_float(frame, "rot", &(out->frames[i].rot));
	}

	
	config_destroy(&layout_config);
	return 0;
}
예제 #3
0
int main(int argc, char *argv[])
{
  FILE *fp;
  int fd, offset, length, i, j;
  time_t t;
  struct tm *gmt;
  volatile void *cfg, *sts;
  volatile uint64_t *fifo[8];
  volatile uint8_t *rst, *sel;
  volatile uint16_t *cntr;
  int32_t type = 2;
  uint64_t *buffer;
  config_t config;
  config_setting_t *setting, *element;
  char date[12];
  char name[64];
  char zeros[15] = "000000_0000.c2";
  double dialfreq;
  double corr;
  double freq[8] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
  int chan[8] = {1, 1, 1, 1, 1, 1, 1, 1};
  uint8_t value = 0;

  if(argc != 2)
  {
    fprintf(stderr, "Usage: write-c2-files config_file.cfg\n");
    return EXIT_FAILURE;
  }

  config_init(&config);

  if(!config_read_file(&config, argv[1]))
  {
    fprintf(stderr, "Error on line %d in configuration file.\n", config_error_line(&config));
    return EXIT_FAILURE;
  }

  if(!config_lookup_float(&config, "corr", &corr))
  {
    fprintf(stderr, "No 'corr' setting in configuration file.\n");
    return EXIT_FAILURE;
  }

  if(corr < -100.0 || corr > 100.0)
  {
    fprintf(stderr, "Wrong 'corr' setting in configuration file.\n");
    return EXIT_FAILURE;
  }

  setting = config_lookup(&config, "bands");
  if(setting == NULL)
  {
    fprintf(stderr, "No 'bands' setting in configuration file.\n");
    return EXIT_FAILURE;
  }

  length = config_setting_length(setting);

  if(length > 8)
  {
    fprintf(stderr, "More than 8 bands in configuration file.\n");
    return EXIT_FAILURE;
  }

  if(length < 1)
  {
    fprintf(stderr, "Less than 1 band in configuration file.\n");
    return EXIT_FAILURE;
  }

  for(i = 0; i < length; ++i)
  {
    element = config_setting_get_elem(setting, i);

    if(!config_setting_lookup_float(element, "freq", &freq[i]))
    {
      fprintf(stderr, "No 'freq' setting in element %d.\n", i);
      return EXIT_FAILURE;
    }

    if(!config_setting_lookup_int(element, "chan", &chan[i]))
    {
      fprintf(stderr, "No 'chan' setting in element %d.\n", i);
      return EXIT_FAILURE;
    }

    if(chan[i] < 1 || chan[i] > 2)
    {
      fprintf(stderr, "Wrong 'chan' setting in element %d.\n", i);
      return EXIT_FAILURE;
    }

    value |= (chan[i] - 1) << i;
  }

  t = time(NULL);
  if((gmt = gmtime(&t)) == NULL)
  {
    fprintf(stderr, "Cannot convert time.\n");
    return EXIT_FAILURE;
  }

  if((fd = open("/dev/mem", O_RDWR)) < 0)
  {
    fprintf(stderr, "Cannot open /dev/mem.\n");
    return EXIT_FAILURE;
  }

  sts = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x40000000);
  cfg = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x40001000);

  for(i = 0; i < 8; ++i)
  {
    fifo[i] = mmap(NULL, 8*sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x40002000 + i * 0x1000);
    *(uint32_t *)(cfg + 8 + i * 4) = (uint32_t)floor((1.0 + 1.0e-6 * corr) * freq[i] / 125.0 * (1<<30) + 0.5);
  }

  rst = (uint8_t *)(cfg + 0);
  sel = (uint8_t *)(cfg + 4);
  cntr = (uint16_t *)(sts + 12);

  *sel = value;

  *rst |= 1;
  *rst &= ~1;

  offset = 0;
  buffer = malloc(45000 * 8 * 8);
  memset(buffer, 0, 45000 * 8 * 8);

  while(offset < 42000)
  {
    while(*cntr < 500) usleep(300000);

    for(i = 0; i < 250; ++i)
    {
      for(j = 0; j < 8; ++j)
      {
        buffer[j * 45000 + offset + i] = *fifo[j];
      }
    }

    offset += 250;
  }

  for(i = 0; i < length; ++i)
  {
    dialfreq = freq[i] - 0.0015;
    strftime(date, 12, "%y%m%d_%H%M", gmt);
    sprintf(name, "wspr_%d_%d_%d_%s.c2", i, (uint32_t)(dialfreq * 1.0e6), chan[i], date);
    if((fp = fopen(name, "wb")) == NULL)
    {
      fprintf(stderr, "Cannot open output file %s.\n", name);
      return EXIT_FAILURE;
    }
    fwrite(zeros, 1, 14, fp);
    fwrite(&type, 1, 4, fp);
    fwrite(&dialfreq, 1, 8, fp);
    fwrite(&buffer[i * 45000], 1, 45000 * 8, fp);
    fclose(fp);
  }

  return EXIT_SUCCESS;
}
예제 #4
0
int settings_load(struct user_settings *s, const char *patharg)
{
    config_t cfg[1];
    config_setting_t *setting;
    const char *str;
    
    /* Load default settings */
    ui_defaults(s);
    tox_defaults(s);
	key_defaults(s);
#ifdef _AUDIO
    audio_defaults(s);
#endif
    
    config_init(cfg);

    char path[MAX_STR_SIZE];

    /* use default config file path */
    if (patharg == NULL) {
        char *user_config_dir = get_user_config_dir();
        snprintf(path, sizeof(path), "%s%stoxic.conf", user_config_dir, CONFIGDIR);
        free(user_config_dir);

        /* make sure path exists or is created on first time running */
        FILE *fp = fopen(path, "r");
        if (fp == NULL) {
            if ((fp = fopen(path, "w")) == NULL)
                return -1;
        }

        fclose(fp);
    } else {
        snprintf(path, sizeof(path), "%s", patharg);
    }
    
    if (!config_read_file(cfg, path)) {
        config_destroy(cfg);
        return -1;
    }
    
    /* ui */
    if ((setting = config_lookup(cfg, ui_strings.self)) != NULL) {
        config_setting_lookup_bool(setting, ui_strings.timestamps, &s->timestamps);
        config_setting_lookup_bool(setting, ui_strings.alerts, &s->alerts);
        config_setting_lookup_bool(setting, ui_strings.autolog, &s->autolog);
        config_setting_lookup_bool(setting, ui_strings.native_colors, &s->colour_theme);
        
        config_setting_lookup_int(setting, ui_strings.history_size, &s->history_size);
        config_setting_lookup_int(setting, ui_strings.time_format, &s->time);
        s->time = s->time == TIME_24 || s->time == TIME_12 ? s->time : TIME_24; /* Check defaults */
    }
    
    if ((setting = config_lookup(cfg, tox_strings.self)) != NULL) {
        if ( config_setting_lookup_string(setting, tox_strings.download_path, &str) ) {
            strcpy(s->download_path, str);
        }
    }
	/* keys */
	if((setting = config_lookup(cfg, key_strings.self)) != NULL) {
	   const char* tmp = NULL;
	   if(config_setting_lookup_string(setting, key_strings.next_tab, &tmp)) s->key_next_tab = key_parse(&tmp);
	   if(config_setting_lookup_string(setting, key_strings.prev_tab, &tmp)) s->key_prev_tab = key_parse(&tmp);
	   if(config_setting_lookup_string(setting, key_strings.scroll_line_up, &tmp)) s->key_scroll_line_up = key_parse(&tmp);
	   if(config_setting_lookup_string(setting, key_strings.scroll_line_down, &tmp)) s->key_scroll_line_down= key_parse(&tmp);
	   if(config_setting_lookup_string(setting, key_strings.half_page_up, &tmp)) s->key_half_page_up = key_parse(&tmp);
	   if(config_setting_lookup_string(setting, key_strings.half_page_down, &tmp)) s->key_half_page_down = key_parse(&tmp);
	   if(config_setting_lookup_string(setting, key_strings.page_bottom, &tmp)) s->key_page_bottom = key_parse(&tmp);
	   if(config_setting_lookup_string(setting, key_strings.peer_list_up, &tmp)) s->key_peer_list_up = key_parse(&tmp);
	   if(config_setting_lookup_string(setting, key_strings.peer_list_down, &tmp)) s->key_peer_list_down = key_parse(&tmp);
	}	   
    
#ifdef _AUDIO
    if ((setting = config_lookup(cfg, audio_strings.self)) != NULL) {
        config_setting_lookup_int(setting, audio_strings.input_device, &s->audio_in_dev);
        s->audio_in_dev = s->audio_in_dev < 0 || s->audio_in_dev > MAX_DEVICES ? 0 : s->audio_in_dev;
        
        config_setting_lookup_int(setting, audio_strings.output_device, &s->audio_out_dev);
        s->audio_out_dev = s->audio_out_dev < 0 || s->audio_out_dev > MAX_DEVICES ? 0 : s->audio_out_dev;
        
        config_setting_lookup_float(setting, audio_strings.VAD_treshold, &s->VAD_treshold);
    }    
#endif

#ifdef _SOUND_NOTIFY
    if ((setting = config_lookup(cfg, sound_strings.self)) != NULL) {
        if ( (config_setting_lookup_string(setting, sound_strings.error, &str) != CONFIG_TRUE) ||
                !set_sound(error, str) ) {
            if (strcasecmp(str, NO_SOUND) != 0)
                set_sound(error, PACKAGE_DATADIR "/sounds/Error.wav");
        }
        
        if ( !config_setting_lookup_string(setting, sound_strings.user_log_in, &str) ||
                !set_sound(user_log_in, str) ) {
            if (strcasecmp(str, NO_SOUND) != 0)
                set_sound(user_log_in, PACKAGE_DATADIR "/sounds/ContactLogsIn.wav");
        }
        
        if ( !config_setting_lookup_string(setting, sound_strings.self_log_in, &str) ||
                !set_sound(self_log_in, str) ) {
            if (strcasecmp(str, NO_SOUND) != 0)
                set_sound(self_log_in, PACKAGE_DATADIR "/sounds/LogIn.wav");
        }

        if ( !config_setting_lookup_string(setting, sound_strings.user_log_out, &str) ||
                !set_sound(user_log_out, str) ) {
            if (strcasecmp(str, NO_SOUND) != 0)
                set_sound(user_log_out, PACKAGE_DATADIR "/sounds/ContactLogsOut.wav");
        }

        if ( !config_setting_lookup_string(setting, sound_strings.self_log_out, &str) ||
                !set_sound(self_log_out, str) ) {
            if (strcasecmp(str, NO_SOUND) != 0)
                set_sound(self_log_out, PACKAGE_DATADIR "/sounds/LogOut.wav");
        }
        
        if ( !config_setting_lookup_string(setting, sound_strings.call_incoming, &str) ||
                !set_sound(call_incoming, str) ) {
            if (strcasecmp(str, NO_SOUND) != 0)
                set_sound(call_incoming, PACKAGE_DATADIR "/sounds/IncomingCall.wav");
        }
        
        if ( !config_setting_lookup_string(setting, sound_strings.call_outgoing, &str) ||
                !set_sound(call_outgoing, str) ) {
            if (strcasecmp(str, NO_SOUND) != 0)
                set_sound(call_outgoing, PACKAGE_DATADIR "/sounds/OutgoingCall.wav");
        }
        
        if ( !config_setting_lookup_string(setting, sound_strings.generic_message, &str) ||
                !set_sound(generic_message, str) ) {
            if (strcasecmp(str, NO_SOUND) != 0)
                set_sound(generic_message, PACKAGE_DATADIR "/sounds/NewMessage.wav");
        }
        
        if ( !config_setting_lookup_string(setting, sound_strings.transfer_pending, &str) ||
                !set_sound(transfer_pending, str) ) {
            if (strcasecmp(str, NO_SOUND) != 0)
                set_sound(transfer_pending, PACKAGE_DATADIR "/sounds/TransferPending.wav");
        }
        
        if ( !config_setting_lookup_string(setting, sound_strings.transfer_completed, &str) ||
                !set_sound(transfer_completed, str) ) {
            if (strcasecmp(str, NO_SOUND) != 0)
                set_sound(transfer_completed, PACKAGE_DATADIR "/sounds/TransferComplete.wav");
        }
    }
    else {
        set_sound(error, PACKAGE_DATADIR "/sounds/Error.wav");
        set_sound(user_log_in, PACKAGE_DATADIR "/sounds/ContactLogsIn.wav");
        set_sound(self_log_in, PACKAGE_DATADIR "/sounds/LogIn.wav");
        set_sound(user_log_out, PACKAGE_DATADIR "/sounds/ContactLogsOut.wav");
        set_sound(self_log_out, PACKAGE_DATADIR "/sounds/LogOut.wav");
        set_sound(call_incoming, PACKAGE_DATADIR "/sounds/IncomingCall.wav");
        set_sound(call_outgoing, PACKAGE_DATADIR "/sounds/OutgoingCall.wav");
        set_sound(generic_message, PACKAGE_DATADIR "/sounds/NewMessage.wav");
        set_sound(transfer_pending, PACKAGE_DATADIR "/sounds/TransferPending.wav");
        set_sound(transfer_completed, PACKAGE_DATADIR "/sounds/TransferComplete.wav");
    }
#endif

    config_destroy(cfg);
    return 0;
}
예제 #5
0
파일: example1.c 프로젝트: 3van/libconfig
int main(int argc, char **argv)
{
  config_t cfg;
  config_setting_t *setting;
  const char *str;

  config_init(&cfg);

  /* Read the file. If there is an error, report it and exit. */
  if(! config_read_file(&cfg, "example.cfg"))
  {
    fprintf(stderr, "%s:%d - %s\n", config_error_file(&cfg),
            config_error_line(&cfg), config_error_text(&cfg));
    config_destroy(&cfg);
    return(EXIT_FAILURE);
  }

  /* Get the store name. */
  if(config_lookup_string(&cfg, "name", &str))
    printf("Store name: %s\n\n", str);
  else
    fprintf(stderr, "No 'name' setting in configuration file.\n");

  /* Output a list of all books in the inventory. */
  setting = config_lookup(&cfg, "inventory.books");
  if(setting != NULL)
  {
    int count = config_setting_length(setting);
    int i;

    printf("%-30s  %-30s   %-6s  %s\n", "TITLE", "AUTHOR", "PRICE", "QTY");

    for(i = 0; i < count; ++i)
    {
      config_setting_t *book = config_setting_get_elem(setting, i);

      /* Only output the record if all of the expected fields are present. */
      const char *title, *author;
      double price;
      int qty;

      if(!(config_setting_lookup_string(book, "title", &title)
           && config_setting_lookup_string(book, "author", &author)
           && config_setting_lookup_float(book, "price", &price)
           && config_setting_lookup_int(book, "qty", &qty)))
        continue;

      printf("%-30s  %-30s  $%6.2f  %3d\n", title, author, price, qty);
    }
    putchar('\n');
  }

  /* Output a list of all movies in the inventory. */
  setting = config_lookup(&cfg, "inventory.movies");
  if(setting != NULL)
  {
    unsigned int count = config_setting_length(setting);
    unsigned int i;

    printf("%-30s  %-10s   %-6s  %s\n", "TITLE", "MEDIA", "PRICE", "QTY");
    for(i = 0; i < count; ++i)
    {
      config_setting_t *movie = config_setting_get_elem(setting, i);

      /* Only output the record if all of the expected fields are present. */
      const char *title, *media;
      double price;
      int qty;

      if(!(config_setting_lookup_string(movie, "title", &title)
           && config_setting_lookup_string(movie, "media", &media)
           && config_setting_lookup_float(movie, "price", &price)
           && config_setting_lookup_int(movie, "qty", &qty)))
        continue;

      printf("%-30s  %-10s  $%6.2f  %3d\n", title, media, price, qty);
    }
    putchar('\n');
  }

  config_destroy(&cfg);
  return(EXIT_SUCCESS);
}
예제 #6
0
void SetValidationParams() {

	//init parameters
	config_t cfg;
	config_setting_t *setting;
	char settingName[50];
	char configFile[30];
	char settingFather[50];

	int EXITO;
	int DEFAULT = false;

	// Reservar memoria
	// inicializar parámetros de modelo de fondo y de validación

	ValBGParams = (BGModelParams *) malloc(sizeof(BGModelParams));
	if (!ValBGParams) {
		error(4);
		exit(1);
	}

	valParams = (ValParams*) malloc(sizeof(ValParams));
	if (!valParams) {
		error(4);
		exit(1);
	}

	fprintf(stderr, "\nCargando parámetros de Validación:");
	fprintf(stderr,
			"\nCargando parámetros de umbralización y limpieza de primer plano...");

	config_init(&cfg);

	sprintf(configFile, "config.cfg");

	/* Leer archivo. si hay un error, informar y cargar configuración por defecto */
	if (!config_read_file(&cfg, configFile)) {
		fprintf(stderr, "%s:%d - %s\n", config_error_file(&cfg),
				config_error_line(&cfg), config_error_text(&cfg));

		fprintf(stderr, "Error al acceder al fichero de configuración %s .\n"
			" Estableciendo valores por defecto.\n", configFile);
		DefaultValParams( );

	} else {
		sprintf(settingFather, "Procesado");
		setting = config_lookup(&cfg, settingFather);
		/* Si no se se encuentra la setting o bien existe la variable hijo Auto y ésta es true, se establecen TODOS los valores por defecto.*/
		if (!setting) {
			fprintf(stderr, "Error.No se ha podido leer el campo %s.\n"
				" Estableciendo valores por defecto.\n", settingFather);
			DEFAULT = true;
		} else {
			sprintf(settingName, "Auto");
			/* Obtener el valor */
			EXITO = config_setting_lookup_bool(setting, settingName, &DEFAULT);
			if (!EXITO)
				DEFAULT = true;
			else if (EXITO && DEFAULT) {
				fprintf(stderr, "\n Opción Auto activada para el campo %s.\n"
					" Estableciendo valores por defecto.\n", settingFather);
			} else if (EXITO && !DEFAULT)
				fprintf(
						stderr,
						"\n Opción Auto desactivada para el campo %s.\n"
							" Estableciendo valores del fichero de configuración.\n",
						settingFather);
		}
		if (DEFAULT) {
			DefaultValParams();
		}
		// si el modo auto del padre no está activado comprobar si lo está el del hijo.
		else {

			// hijo 1
			sprintf(settingFather, "Procesado.Validacion");
			setting = config_lookup(&cfg, settingFather);
			/* Si no se se encuentra la setting o bien existe la variable hijo Auto y ésta es true, se establecen TODOS los valores por defecto.*/
			if (setting != NULL) {
				sprintf(settingName, "Auto");
				/* Obtener el valor */
				EXITO = config_setting_lookup_bool(setting, settingName,
						&DEFAULT);
				if (!EXITO)
					DEFAULT = true;
				else if (EXITO && DEFAULT)
					fprintf(stderr,
							"\n Opción Auto activada para el campo %s.\n"
								" Estableciendo valores por defecto.\n",
							settingFather);
				else if (EXITO && !DEFAULT)
					fprintf(
							stderr,
							"\n Opción Auto desactivada para el campo %s.\n"
								" Estableciendo valores del fichero de configuración.\n",
							settingFather);
			} else {
				DEFAULT = true;
				fprintf(stderr, "Error.No se ha podido leer el campo %s.\n"
					" Estableciendo valores por defecto.\n", settingFather);
			}
			if (DEFAULT) {
				DefaultValParams();
			} else {
				double val;
				sprintf(settingName, "MODEL_TYPE");
				if (!config_setting_lookup_int(setting, settingName,
						&ValBGParams->MODEL_TYPE)) {
					ValBGParams->MODEL_TYPE = MEDIAN_S_UP;
					fprintf(
							stderr,
							"No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
								"Establecer por defecto a %d \n", settingName,
							ValBGParams->MODEL_TYPE);

				}

				sprintf(settingName, "MORFOLOGIA");
				if (!config_setting_lookup_bool(setting, settingName,
						&ValBGParams->MORFOLOGIA)) {
					ValBGParams->MORFOLOGIA = true;
					fprintf(
							stderr,
							"No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
								"Establecer por defecto a %d \n", settingName,
							ValBGParams->MORFOLOGIA);

				}

				sprintf(settingName, "CVCLOSE_ITR");
				if (!config_setting_lookup_int(setting, settingName,
						&ValBGParams->CVCLOSE_ITR)) {
					ValBGParams->CVCLOSE_ITR = 1;
					fprintf(
							stderr,
							"No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
								"Establecer por defecto a %d \n", settingName,
							ValBGParams->CVCLOSE_ITR);

				}

				sprintf(settingName, "MAX_CONTOUR_AREA");
				if (!config_setting_lookup_int(setting, settingName,
						&ValBGParams->MAX_CONTOUR_AREA)) {
					ValBGParams->MAX_CONTOUR_AREA = 0;
					fprintf(
							stderr,
							"No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
								"Establecer por defecto a %d \n", settingName,
							ValBGParams->MAX_CONTOUR_AREA);
				}

				sprintf(settingName, "MIN_CONTOUR_AREA");
				if (!config_setting_lookup_int(setting, settingName,
						&ValBGParams->MIN_CONTOUR_AREA)) {
					ValBGParams->MIN_CONTOUR_AREA = 0; //5
					fprintf(
							stderr,
							"No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
								"Establecer por defecto a %d \n", settingName,
							ValBGParams->MIN_CONTOUR_AREA);

				}

				sprintf(settingName, "HIGHT_THRESHOLD");
				if (!config_setting_lookup_int(setting, settingName,
						&ValBGParams->HIGHT_THRESHOLD)) {
					ValBGParams->HIGHT_THRESHOLD = 20;
					fprintf(
							stderr,
							"No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
								"Establecer por defecto a %d \n",
							settingName, ValBGParams->HIGHT_THRESHOLD);

				} else {
					if ((!ValBGParams->HIGHT_THRESHOLD
							|| ValBGParams->HIGHT_THRESHOLD > 255)) {
						ValBGParams->HIGHT_THRESHOLD = 20;
						fprintf(stderr,
								"El valor de %s está fuera de límites\n "
									"Establecer por defecto %s a %d \n",
								settingName, settingName, ValBGParams->BG_Update);
					}

				}

				sprintf(settingName, "LOW_THRESHOLD");
				if (!config_setting_lookup_int(setting, settingName,
						&ValBGParams->LOW_THRESHOLD)) {
					ValBGParams->LOW_THRESHOLD = 15;
					fprintf(
							stderr,
							"No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
								"Establecer por defecto a %d \n", settingName,
							ValBGParams->LOW_THRESHOLD);
				} else {
					if ((!ValBGParams->LOW_THRESHOLD
							|| ValBGParams->LOW_THRESHOLD > 255)) {
						ValBGParams->LOW_THRESHOLD = 15;
						fprintf(stderr,
								"El valor de %s está fuera de límites\n "
									"Establecer por defecto %s a %d \n",
								settingName, settingName, ValBGParams->BG_Update);
						if (ValBGParams->LOW_THRESHOLD > 50)
							fprintf(stderr,
									"ADVERTENCIA: El valor de %s es muy elevado\n "
										"Establecer por defecto %s a %d \n",
									settingName, settingName,
									ValBGParams->LOW_THRESHOLD);
					}

				}

				fprintf(stderr,"\n Cargando parámetros específicos de validación...");

				sprintf(settingName, "UmbralCirc");
				if (!config_setting_lookup_int(setting, settingName,
						&valParams->UmbralCirc)) {
					valParams->UmbralCirc = 0;
					fprintf(
							stderr,
							"No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
								"Establecer por defecto a %d \n",
							settingName, valParams->UmbralCirc);
				}

				sprintf(settingName, "Umbral_H");
				if (!config_setting_lookup_float(setting, settingName,
						&val)) {
					valParams->Umbral_H = 5; //5
					fprintf(
							stderr,
							"No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
								"Establecer por defecto a %d \n",
							settingName, ValBGParams->MIN_CONTOUR_AREA);

				}else {
					if ((!val
							|| val > 255)) {
						val = 5;
						fprintf(stderr,
								"El valor de %s está fuera de límites\n "
									"Establecer por defecto %s a %0.1f \n",
								settingName, settingName,
								val);
					}
					valParams->Umbral_H = (float)val;
				}

				sprintf(settingName, "Umbral_L");
				if (!config_setting_lookup_float(setting, settingName,
						&val)) {
					valParams->Umbral_L = 5;
					fprintf(
							stderr,
							"No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
								"Establecer por defecto a %d \n",
							settingName, ValBGParams->HIGHT_THRESHOLD);

				} else {
					if ((!val
							|| val > 255)) {
						val = 5;
						fprintf(stderr,
								"El valor de %s está fuera de límites\n "
									"Establecer por defecto %s a %0.1f \n",
								settingName, settingName,
								valParams->Umbral_L);
					}
					valParams->Umbral_L = (float)val;
				}

				sprintf(settingName, "Umbral_MinArea");
				if (!config_setting_lookup_int(setting, settingName,
						&valParams->Umbral_MinArea)) {
					valParams->Umbral_MinArea = 0;
					fprintf(
							stderr,
							"No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
								"Establecer por defecto a %d \n",
							settingName, valParams->Umbral_MinArea);
				}

				sprintf(settingName, "MaxIncLTHIters");
				if (!config_setting_lookup_int(setting, settingName,
						&valParams->MaxIncLTHIters)) {
					valParams->MaxIncLTHIters = 100;
					fprintf(
							stderr,
							"No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
								"Establecer por defecto a %d \n",
							settingName, valParams->MaxIncLTHIters);
				}
				sprintf(settingName, "MaxLowTH");
				if (!config_setting_lookup_int(setting, settingName,
						&valParams->MaxLowTH)) {
					valParams->MaxLowTH = 1000;
					fprintf(
							stderr,
							"No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
								"Establecer por defecto a %d \n",
							settingName, valParams->MaxLowTH);
				}
				sprintf(settingName, "MinLowTH");
				if (!config_setting_lookup_int(setting, settingName,
						&valParams->MinLowTH)) {
					valParams->MinLowTH = 1; // límite inferior para el umbral bajo ( defecto )
					fprintf(
							stderr,
							"No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
								"Establecer por defecto a %d \n",
							settingName, valParams->MinLowTH);
				}

				sprintf(settingName, "CleanGhosts");
				if (!config_setting_lookup_bool(setting, settingName,
						&valParams->CleanGhosts)) {
					valParams->CleanGhosts = false; // límite inferior para el umbral bajo ( defecto )
					fprintf(
							stderr,
							"No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
								"Establecer por defecto a %d \n",
							settingName, valParams->CleanGhosts);
				}

				sprintf(settingName, "umbralCleanGhosts");
				if (!config_setting_lookup_int(setting, settingName,
						&valParams->umbralCleanGhosts)) {

					valParams->umbralCleanGhosts = 10;
					fprintf(
							stderr,
							"No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
								"Establecer por defecto a %d píxels \n",
							settingName, valParams->umbralCleanGhosts );

				}
				else if( valParams->umbralCleanGhosts < 0 ){

					valParams->umbralCleanGhosts = 10;
					fprintf(stderr,
							"El valor de %s está fuera de límites\n "
								"Establecer por defecto %s a %d píxels \n",
							settingName, settingName,
							valParams->umbralCleanGhosts );
				}


			}
		}// fin comprobar auto hijos
	} // fin lectura correcta fichero
	valParams->privateParams = NULL;
	ShowValParams(settingFather);

	//	ShowStatsParams( settingFather );
	config_destroy(&cfg);
}
예제 #7
0
int main(int argc, char *argv[]) {
    config_t cfg;
    config_setting_t *setting;
    const char *base = NULL, *str1, *str2;
    int count, n, boolean_value;
    double ker;
    char *config_file_name = "test.cfg";

    /* Inizializzazione */
    config_init(&cfg);

    if (!config_read_file(&cfg, config_file_name)) {
        fprintf(stderr, "%d - %s\n",
                config_error_line(&cfg),
                config_error_text(&cfg));

        config_destroy(&cfg);

        return(EXIT_FAILURE);
    }

    /* Si verifica l'esistenza di un un valore booleano */
    if (config_lookup_bool(&cfg, "prova", &boolean_value))
            printf("valore booleano: %s\n", boolean_value ? "Yes" : "No");
    else
        printf("boolean_value is not defined\n");

    /* Ricezione di una stringa */
    if (config_lookup_string(&cfg, "filename", &str1))
        printf("   Tipo di file: %s\n", str1);
    else
        printf("No filename setting config file\n");

    setting = config_lookup(&cfg, "rete");

    if (setting != NULL) {
        /* Legge  stringa */
        if (config_setting_lookup_string(setting, "host", &str2))
            printf("           Host: %s\n", str2);
        else
            printf("No host\n");

        if (config_setting_lookup_string(setting, "arch", &str2))
            printf("   Architettura: %s\n", str2);
        else
            printf("No arch\n");
        
        if (config_setting_lookup_float(setting, "kernel", &ker))
            printf(" Kernel version: %f\n", ker);
        else
            printf("No kernel\n");
    }

    setting = config_lookup(&cfg, "negozio.libri");
    if (setting != NULL) {
        /* Legge  stringa */
        if (config_setting_lookup_string(setting, "titolo", &str2))
            printf("         Titolo: %s\n", str2);
        else
            printf("No titolo\n");
    }

    // Quando si lavora con liste o con array si utilizza l'indicizzazione */
    setting = config_lookup(&cfg, "negozio.pizzeria.pizze_da_asporto.[1]");
    if (setting != NULL) {
        /* Legge  stringa */
        if (config_setting_lookup_string(setting, "nome", &str2))
            printf("          Pizza: %s\n", str2);
        else
            printf("No nome\n");
    }


    return(EXIT_SUCCESS);
}
예제 #8
0
static int
odesys_cfg_parse (odesys_t * ode, const config_t * cfg)
/* Simply parse the config object and return an odesys_t object. ode
   object needs to have previously been created - this function
   doesn't allocate memory for it. This function does allocate memory
   for the expval_windows object contained within ode though. */
{
  double hstep, tstart, tend;
  config_setting_t *s;
  int failure = 0;
  int i;

  s = config_lookup (cfg, "odesolver");

  if (s == NULL)
    {
      fprintf (stderr, "Failed to find odesolver section in config.\n");
      return -1;
    }

  if (!(config_setting_lookup_float (s, "hstep", &hstep) &&
	config_setting_lookup_float (s, "eps_rel", &(ode->eps_rel)) &&
	config_setting_lookup_float (s, "eps_abs", &(ode->eps_abs)) &&
	config_setting_lookup_float (s, "y_scale", &(ode->y_scale)) &&
	config_setting_lookup_float (s, "dydx_scale", &(ode->dydx_scale)) &&
	config_setting_lookup_float (s, "tstart", &tstart) &&
	config_setting_lookup_float (s, "tend", &tend)))
    {
      fprintf (stderr,
	       "%s %d: Incomplete/malformed odesolver configuration in file.\n",
	       __func__, __LINE__);
      return -1;
    }

  /* Convert to atomic units. */
  ode->hstep = PS_TO_AU (hstep);
  ode->tstart = PS_TO_AU (tstart);
  ode->tend = PS_TO_AU (tend);

  /* Read expectation value window specifications. */
  s = config_lookup (cfg, "expval");

  if (s == NULL)
    {
      fprintf (stderr,
	       "%s %d: Failed to find expval section in config file.\n",
	       __func__, __LINE__);
      return -1;
    }
  else
    {
      int nwindows = config_setting_length (s);

      if (nwindows < 1)
	{
	  fprintf (stderr,
		   "%s %d: No expecation value windows found in expval section in config file.\n",
		   __func__, __LINE__);
	  return -1;
	}

      ode->expval_windows = odesys_expval_windows_ctor (nwindows);
      if (ode->expval_windows == NULL)
	{
	  fprintf (stderr,
		   "%s %d: Failed to allocate memory for storage of expectation value windows.\n",
		   __func__, __LINE__);
	  return -1;
	}

      for (i = 0; i < nwindows; i++)
	{
	  double tstart, tend;
	  int npoints;
	  config_setting_t *this_window_cfg = config_setting_get_elem (s, i);

	  if (this_window_cfg == NULL)
	    {
	      fprintf (stderr,
		       "%s %d: Failed to find expectation value window in exvpal section of config file.\n",
		       __func__, __LINE__);
	      failure = 1;
	      break;
	    }

	  if (!
	      (config_setting_lookup_float
	       (this_window_cfg, "tstart", &tstart)
	       && config_setting_lookup_float (this_window_cfg, "tend", &tend)
	       && config_setting_lookup_int (this_window_cfg, "npoints",
					     &npoints)))
	    {
	      fprintf (stderr,
		       "%s %d: Expectation value window definition incomplete in config file.\n",
		       __func__, __LINE__);
	      failure = 1;
	      break;
	    }

	  /* We adopt the protocol that tend > tstart for each window,
	     and that the windows don't overlap, and are specified in
	     ascending order of tstart. */
	  if (tend < tstart)
	    {
	      fprintf (stderr,
		       "%s %d: tend < tstart in expectation value window definition %d.\n",
		       __func__, __LINE__, i);
	      failure = 1;
	      break;
	    }

	  tstart = PS_TO_AU (tstart);
	  tend = PS_TO_AU (tend);

	  if (i > 1)
	    {
	      odesys_expval_t *prev_window =
		ode->expval_windows->window[i - 1];

	      if (tstart < prev_window->tend)
		{
		  fprintf (stderr,
			   "%s %d: tstart in expectation value window definition %d is inside previous expectation value window.\n",
			   __func__, __LINE__, i);
		  failure = 1;
		  break;
		}
	    }

	  ode->expval_windows->window[i] =
	    odesys_expval_ctor (ode, tstart, tend, npoints);

	  if (ode->expval_windows->window[i] == NULL)
	    {
	      fprintf (stderr,
		       "%s %d: Unable to allocate storage for expectation value window.\n",
		       __func__, __LINE__);
	      failure = 1;
	      break;
	    }
	}
    }

  if (failure)
    {
      int j;

      for (j = 0; j < i; j++)
	odesys_expval_dtor (ode, ode->expval_windows->window[j]);

      MEMORY_FREE (ode->expval_windows);
      return -1;
    }

  return 0;
}
예제 #9
0
struct node_parameters read_node_parameters(int node, char *scenario_file) {
  // string pointing to scenario file
  char scenario[100];
  strcpy(scenario, "scenarios/");
  strcat(scenario, scenario_file);

  config_t cfg;
  config_init(&cfg);

  // Read the file. If there is an error, report it and exit.
  if (!config_read_file(&cfg, scenario)) {
    printf("Error reading config file on line %i\n", config_error_line(&cfg));
    config_destroy(&cfg);
    exit(1);
  }

  int tmpI;
  double tmpD;
  const char *tmpS;

  // scenario info struct for node
  struct node_parameters np = {};
  char nodestr[100];
  std::string node_num;
  std::stringstream out;
  out << node;
  node_num = out.str();

  // lookup specific node
  strcpy(nodestr, "node");
  strcat(nodestr, node_num.c_str());
  config_setting_t *node_config = config_lookup(&cfg, nodestr);

  // read CORNET IP address for the node
  if (config_setting_lookup_string(node_config, "TARGET_IP", &tmpS))
    strcpy(np.TARGET_IP, tmpS);
  else
    strcpy(np.TARGET_IP, "10.0.0.3");

  // read CORNET IP address for the node
  if (config_setting_lookup_string(node_config, "CORNET_IP", &tmpS))
    strcpy(np.CORNET_IP, tmpS);
  else
    strcpy(np.CORNET_IP, "192.168.1.12");

  // read type of node
  if (config_setting_lookup_string(node_config, "type", &tmpS)) {
    // printf("\nNode type: %s\n", tmpS);
    if (strcmp(tmpS, "CR") == 0) {
      np.type = CR;
      np.cr_type = ecr;
      // If node is a CR, lookup whether is uses the ECR or python
      if (config_setting_lookup_string(node_config, "cr_type", &tmpS)) {
        if (strcmp(tmpS, "python") == 0) {
          np.cr_type = python;
          // python radios are specified by the "python_file" field in the
          // scenario file
          if (config_setting_lookup_string(node_config, "python_file", &tmpS)) {
            strcpy(np.python_file, tmpS);
            // check for optional command line arguments and add them to
            // np.arguments if found
            const config_setting_t *arguments;
            char path[100];
            strcpy(path, nodestr);
            strcat(path, ".arguments");
            arguments = config_lookup(&cfg, path);
            np.num_arguments = 0;
            if (arguments != NULL) {
              np.num_arguments = config_setting_length(arguments);
              for (int i = 0; i < np.num_arguments; i++) {
                tmpS = config_setting_get_string_elem(arguments, i);
                strcpy(np.arguments[i], tmpS);
              }
            } else
              printf("arguments not found\n");
          } else {
            printf("A python radio requires a python file.\n");
          }
        }
        // Possibly add more types later, but for now if not python, then radio
        // must be ECR-based
        // and the engine to use is specified by the "CE" field
        else {
          if (config_setting_lookup_string(node_config, "CE", &tmpS))
            strcpy(np.CE, tmpS);
          else {
            printf(
                "Configuration of a node did not specify a cognitive engine");
            exit(1);
          }
        }
      }
    } else if (strcmp(tmpS, "interferer") == 0)
      np.type = interferer;
  }

  // read all possible node settings
  if (config_setting_lookup_string(node_config, "CRTS_IP", &tmpS))
    strcpy(np.CRTS_IP, tmpS);
  else
    strcpy(np.CRTS_IP, "10.0.0.2");

  if (config_setting_lookup_int(node_config, "print_metrics", &tmpI))
    np.print_metrics = (int)tmpI;

  if (config_setting_lookup_int(node_config, "log_phy_rx", &tmpI))
    np.log_phy_rx = (int)tmpI;

  if (config_setting_lookup_int(node_config, "log_phy_tx", &tmpI))
    np.log_phy_tx = (int)tmpI;

  if (config_setting_lookup_int(node_config, "log_net_rx", &tmpI))
    np.log_net_rx = (int)tmpI;

  if (config_setting_lookup_string(node_config, "phy_rx_log_file", &tmpS))
    strcpy(np.phy_rx_log_file, tmpS);

  if (config_setting_lookup_string(node_config, "phy_tx_log_file", &tmpS))
    strcpy(np.phy_tx_log_file, tmpS);

  if (config_setting_lookup_string(node_config, "net_rx_log_file", &tmpS))
    strcpy(np.net_rx_log_file, tmpS);

  if (config_setting_lookup_int(node_config, "generate_octave_logs", &tmpI))
    np.generate_octave_logs = (int)tmpI;

  if (config_setting_lookup_int(node_config, "generate_python_logs", &tmpI))
    np.generate_python_logs = (int)tmpI;

  if (config_setting_lookup_float(node_config, "ce_timeout_ms", &tmpD))
    np.ce_timeout_ms = tmpD;

  if (config_setting_lookup_string(node_config, "duplex", &tmpS)) {
    if (!strcmp(tmpS, "FDD"))
      np.duplex = FDD;
    else if (!strcmp(tmpS, "TDD"))
      np.duplex = TDD;
    else if (!strcmp(tmpS, "HD"))
      np.duplex = HD;
    else
      np.duplex = FDD;
  }

  if (config_setting_lookup_float(node_config, "rx_freq", &tmpD))
    np.rx_freq = tmpD;

  if (config_setting_lookup_float(node_config, "rx_rate", &tmpD))
    np.rx_rate = tmpD;
  else
    np.rx_rate = 1e6;

  if (config_setting_lookup_float(node_config, "rx_gain", &tmpD))
    np.rx_gain = tmpD;
  else
    np.rx_gain = 20.0;

  if (config_setting_lookup_int(node_config, "rx_subcarriers", &tmpI))
    np.rx_subcarriers = (int)tmpI;
  else
    np.rx_subcarriers = 64;

  if (config_setting_lookup_string(node_config, "rx_subcarrier_alloc_method",
                                   &tmpS)) {
    // subcarrier allocation is being defined in a standard way
    if (!strcmp(tmpS, "standard")) {
      np.rx_subcarrier_alloc_method = STANDARD_SUBCARRIER_ALLOC;

      int rx_guard_subcarriers;
      int rx_central_nulls;
      int rx_pilot_freq;
      if (config_setting_lookup_int(node_config, "rx_guard_subcarriers", &tmpI))
        rx_guard_subcarriers = tmpI;

      if (config_setting_lookup_int(node_config, "rx_central_nulls", &tmpI))
        rx_central_nulls = tmpI;

      if (config_setting_lookup_int(node_config, "rx_pilot_freq", &tmpI))
        rx_pilot_freq = tmpI;

      for (int i = 0; i < np.rx_subcarriers; i++) {
        // central band nulls
        if (i < rx_central_nulls / 2 ||
            np.rx_subcarriers - i - 1 < rx_central_nulls / 2)
          np.rx_subcarrier_alloc[i] = OFDMFRAME_SCTYPE_NULL;
        // guard band nulls
        else if (i + 1 > np.rx_subcarriers / 2 - rx_guard_subcarriers &&
                 i < np.rx_subcarriers / 2 + rx_guard_subcarriers)
          np.rx_subcarrier_alloc[i] = OFDMFRAME_SCTYPE_NULL;
        // pilot subcarriers (based on distance from center)
        else if (abs((int)((float)np.rx_subcarriers / 2.0 - (float)i - 0.5)) %
                     rx_pilot_freq ==
                 0)
          np.rx_subcarrier_alloc[i] = OFDMFRAME_SCTYPE_PILOT;
        // data subcarriers
        else
          np.rx_subcarrier_alloc[i] = OFDMFRAME_SCTYPE_DATA;
      }
    }

    // subcarrier allocation is completely custom
    else if (!strcmp(tmpS, "custom")) {
      np.rx_subcarrier_alloc_method = CUSTOM_SUBCARRIER_ALLOC;
      config_setting_t *rx_subcarrier_alloc =
          config_setting_get_member(node_config, "rx_subcarrier_alloc");

      char type_str[9] = "sc_type_";
      char num_str[8] = "sc_num_";
      char sc_type[16];
      char sc_num[16];
      int i = 1;
      int j = 0;
      int offset = np.rx_subcarriers / 2;
      sprintf(sc_type, "%s%d", type_str, i);
      // read in a custom initial subcarrier allocation
      while (
          config_setting_lookup_string(rx_subcarrier_alloc, sc_type, &tmpS)) {
        // read the number of subcarriers into tmpI
        sprintf(sc_num, "%s%d", num_str, i);
        tmpI = 1;
        config_setting_lookup_int(rx_subcarrier_alloc, sc_num, &tmpI);
        // set the subcarrier type based on the number specified
        if (!strcmp(tmpS, "null")) {
          for (int k = 0; k < tmpI; k++) {
            if (j >= (np.rx_subcarriers) / 2)
              offset = -(np.rx_subcarriers / 2);
            np.rx_subcarrier_alloc[j + offset] = OFDMFRAME_SCTYPE_NULL;
            j++;
          }
        }
        if (!strcmp(tmpS, "pilot")) {
          for (int k = 0; k < tmpI; k++) {
            if (j >= (np.rx_subcarriers) / 2)
              offset = -(np.rx_subcarriers / 2);
            np.rx_subcarrier_alloc[j + offset] = OFDMFRAME_SCTYPE_PILOT;
            j++;
          }
        }
        if (!strcmp(tmpS, "data")) {
          for (int k = 0; k < tmpI; k++) {
            if (j >= (np.rx_subcarriers) / 2)
              offset = -(np.rx_subcarriers / 2);
            np.rx_subcarrier_alloc[j + offset] = OFDMFRAME_SCTYPE_DATA;
            j++;
          }
        }
        if (j > 2048) {
          printf("The number of subcarriers specified was too high!\n");
          exit(1);
        }
        i++;
        sprintf(sc_type, "%s%d", type_str, i);
      }
    } else
      np.rx_subcarrier_alloc_method = LIQUID_DEFAULT_SUBCARRIER_ALLOC;
  }

  if (config_setting_lookup_int(node_config, "rx_cp_len", &tmpI))
    np.rx_cp_len = (int)tmpI;
  else
    np.rx_cp_len = 16;

  if (config_setting_lookup_int(node_config, "rx_taper_len", &tmpI))
    np.rx_taper_len = (int)tmpI;
  else
    np.rx_taper_len = 4;

  if (config_setting_lookup_float(node_config, "tx_freq", &tmpD))
    np.tx_freq = tmpD;

  if (config_setting_lookup_float(node_config, "tx_rate", &tmpD))
    np.tx_rate = tmpD;
  else
    np.rx_rate = 1e6;

  if (config_setting_lookup_float(node_config, "tx_gain_soft", &tmpD))
    np.tx_gain_soft = tmpD;
  else
    np.tx_gain_soft = -12.0;

  if (config_setting_lookup_float(node_config, "tx_gain", &tmpD))
    np.tx_gain = tmpD;
  else
    np.tx_gain = 20.0;

  if (config_setting_lookup_int(node_config, "tx_subcarriers", &tmpI))
    np.tx_subcarriers = (int)tmpI;
  else
    np.tx_subcarriers = 64;

  if (config_setting_lookup_string(node_config, "tx_subcarrier_alloc_method",
                                   &tmpS)) {
    // subcarrier allocation is being defined in a standard way
    if (!strcmp(tmpS, "standard")) {
      np.tx_subcarrier_alloc_method = STANDARD_SUBCARRIER_ALLOC;

      int tx_guard_subcarriers;
      int tx_central_nulls;
      int tx_pilot_freq;
      if (config_setting_lookup_int(node_config, "tx_guard_subcarriers", &tmpI))
        tx_guard_subcarriers = tmpI;

      if (config_setting_lookup_int(node_config, "tx_central_nulls", &tmpI))
        tx_central_nulls = tmpI;

      if (config_setting_lookup_int(node_config, "tx_pilot_freq", &tmpI))
        tx_pilot_freq = tmpI;

      for (int i = 0; i < np.tx_subcarriers; i++) {
        // central band nulls
        if (i < tx_central_nulls / 2 ||
            np.tx_subcarriers - i - 1 < tx_central_nulls / 2)
          np.tx_subcarrier_alloc[i] = OFDMFRAME_SCTYPE_NULL;
        // guard band nulls
        else if (i + 1 > np.tx_subcarriers / 2 - tx_guard_subcarriers &&
                 i < np.tx_subcarriers / 2 + tx_guard_subcarriers)
          np.tx_subcarrier_alloc[i] = OFDMFRAME_SCTYPE_NULL;
        // pilot subcarriers
        else if (abs((int)((float)np.tx_subcarriers / 2.0 - (float)i - 0.5)) %
                     tx_pilot_freq ==
                 0)
          np.tx_subcarrier_alloc[i] = OFDMFRAME_SCTYPE_PILOT;
        // data subcarriers
        else
          np.tx_subcarrier_alloc[i] = OFDMFRAME_SCTYPE_DATA;
      }
    }

    // subcarrier allocation is completely custom
    else if (!strcmp(tmpS, "custom")) {
      np.tx_subcarrier_alloc_method = CUSTOM_SUBCARRIER_ALLOC;
      config_setting_t *tx_subcarrier_alloc =
          config_setting_get_member(node_config, "tx_subcarrier_alloc");

      char type_str[9] = "sc_type_";
      char num_str[8] = "sc_num_";
      char sc_type[16];
      char sc_num[16];
      int i = 1;
      int j = 0;
      int offset = np.tx_subcarriers / 2;
      sprintf(sc_type, "%s%d", type_str, i);
      // read in a custom initial subcarrier allocation
      while (
          config_setting_lookup_string(tx_subcarrier_alloc, sc_type, &tmpS)) {
        // read the number of subcarriers into tmpI
        sprintf(sc_num, "%s%d", num_str, i);
        tmpI = 1;
        config_setting_lookup_int(tx_subcarrier_alloc, sc_num, &tmpI);
        // set the subcarrier type based on the number specified
        if (!strcmp(tmpS, "null")) {
          for (int k = 0; k < tmpI; k++) {
            if (j >= (np.tx_subcarriers) / 2)
              offset = -(np.tx_subcarriers / 2);
            np.tx_subcarrier_alloc[j + offset] = OFDMFRAME_SCTYPE_NULL;
            j++;
          }
        }
        if (!strcmp(tmpS, "pilot")) {
          for (int k = 0; k < tmpI; k++) {
            if (j >= (np.tx_subcarriers) / 2)
              offset = -(np.tx_subcarriers / 2);
            np.tx_subcarrier_alloc[j + offset] = OFDMFRAME_SCTYPE_PILOT;
            j++;
          }
        }
        if (!strcmp(tmpS, "data")) {
          for (int k = 0; k < tmpI; k++) {
            if (j >= (np.tx_subcarriers) / 2)
              offset = -(np.tx_subcarriers / 2);
            np.tx_subcarrier_alloc[j + offset] = OFDMFRAME_SCTYPE_DATA;
            j++;
          }
        }
        if (j > 2048) {
          printf("The number of subcarriers specified was too high!\n");
          exit(1);
        }
        i++;
        sprintf(sc_type, "%s%d", type_str, i);
      }
    } else
      np.tx_subcarrier_alloc_method = LIQUID_DEFAULT_SUBCARRIER_ALLOC;
  }

  if (config_setting_lookup_int(node_config, "tx_cp_len", &tmpI))
    np.tx_cp_len = (int)tmpI;
  else
    np.tx_cp_len = 16;

  if (config_setting_lookup_int(node_config, "tx_taper_len", &tmpI))
    np.tx_taper_len = (int)tmpI;
  else
    np.tx_taper_len = 4;

  // default tx modulation is BPSK
  np.tx_modulation = LIQUID_MODEM_BPSK;
  if (config_setting_lookup_string(node_config, "tx_modulation", &tmpS)) {

    // Iterate through every liquid modulation scheme
    // and if the string matches, then assign that scheme.
    // See liquid soruce: src/modem/src/modem_utilities.c
    // for definition of modulation_types
    for (int k = 0; k < LIQUID_MODEM_NUM_SCHEMES; k++) {
      if (!strcmp(tmpS, modulation_types[k].name))
        np.tx_modulation = modulation_types[k].scheme;
    }
  }

  // default tx CRC32
  np.tx_crc = LIQUID_CRC_32;
  if (config_setting_lookup_string(node_config, "tx_crc", &tmpS)) {

    // Iterate through every liquid CRC
    // and if the string matches, then assign that CRC.
    // See liquid soruce: src/fec/src/crc.c
    // for definition of crc_scheme_str
    for (int k = 0; k < LIQUID_CRC_NUM_SCHEMES; k++) {
      if (!strcmp(tmpS, crc_scheme_str[k][0]))
        np.tx_crc = k;
    }
  }

  // default tx FEC0 is Hamming 12/8
  np.tx_fec0 = LIQUID_FEC_HAMMING128;
  if (config_setting_lookup_string(node_config, "tx_fec0", &tmpS)) {

    // Iterate through every liquid FEC
    // and if the string matches, then assign that FEC.
    // See liquid soruce: src/fec/src/fec.c
    // for definition of fec_scheme_str
    for (int k = 0; k < LIQUID_FEC_NUM_SCHEMES; k++) {
      if (!strcmp(tmpS, fec_scheme_str[k][0]))
        np.tx_fec0 = k;
    }
  }

  // default rx FEC1 is none
  np.tx_fec1 = LIQUID_FEC_NONE;
  if (config_setting_lookup_string(node_config, "tx_fec1", &tmpS)) {

    // Iterate through every liquid FEC
    // and if the string matches, then assign that FEC.
    // See liquid soruce: src/fec/src/fec.c
    // for definition of fec_scheme_str
    for (int k = 0; k < LIQUID_FEC_NUM_SCHEMES; k++) {
      if (!strcmp(tmpS, fec_scheme_str[k][0]))
        np.tx_fec1 = k;
    }
  }

  if (config_setting_lookup_float(node_config, "tx_delay_us", &tmpD))
    np.tx_delay_us = tmpD;
  else
    np.tx_delay_us = 1e3;

  if (config_setting_lookup_string(node_config, "interference_type", &tmpS)) {
    if (!strcmp(tmpS, "CW"))
      np.interference_type = CW;
    if (!strcmp(tmpS, "AWGN"))
      np.interference_type = NOISE;
    if (!strcmp(tmpS, "GMSK"))
      np.interference_type = GMSK;
    if (!strcmp(tmpS, "RRC"))
      np.interference_type = RRC;
    if (!strcmp(tmpS, "OFDM"))
      np.interference_type = OFDM;
  }

  if (config_setting_lookup_float(node_config, "period", &tmpD))
    np.period = tmpD;

  if (config_setting_lookup_float(node_config, "duty_cycle", &tmpD))
    np.duty_cycle = tmpD;

  // ======================================================
  // process frequency hopping parameters
  // ======================================================
  if (config_setting_lookup_string(node_config, "tx_freq_hop_type", &tmpS)) {
    if (!strcmp(tmpS, "NONE"))
      np.tx_freq_hop_type = NONE;
    if (!strcmp(tmpS, "ALTERNATING"))
      np.tx_freq_hop_type = ALTERNATING;
    if (!strcmp(tmpS, "SWEEP"))
      np.tx_freq_hop_type = SWEEP;
    if (!strcmp(tmpS, "RANDOM"))
      np.tx_freq_hop_type = RANDOM;
  }

  if (config_setting_lookup_float(node_config, "tx_freq_hop_min", &tmpD))
    np.tx_freq_hop_min = tmpD;

  if (config_setting_lookup_float(node_config, "tx_freq_hop_max", &tmpD))
    np.tx_freq_hop_max = tmpD;

  if (config_setting_lookup_float(node_config, "tx_freq_hop_dwell_time", &tmpD))
    np.tx_freq_hop_dwell_time = tmpD;

  if (config_setting_lookup_float(node_config, "tx_freq_hop_increment", &tmpD))
    np.tx_freq_hop_increment = tmpD;

  return np;
}
예제 #10
0
int settings_load(struct user_settings *s, const char *patharg)
{
    config_t cfg[1];
    config_setting_t *setting;
    const char *str = NULL;

    /* Load default settings */
    ui_defaults(s);
    tox_defaults(s);
    key_defaults(s);

#ifdef AUDIO
    audio_defaults(s);
#endif

    config_init(cfg);

    char path[MAX_STR_SIZE];

    /* use default config file path */
    if (patharg == NULL) {
        char *user_config_dir = get_user_config_dir();
        snprintf(path, sizeof(path), "%s%stoxic.conf", user_config_dir, CONFIGDIR);
        free(user_config_dir);

        /* make sure path exists or is created on first time running */
        if (!file_exists(path)) {
            FILE *fp = fopen(path, "w");

            if (fp == NULL)
                return -1;

            fclose(fp);
        }
    } else {
        snprintf(path, sizeof(path), "%s", patharg);
    }

    if (!config_read_file(cfg, path)) {
        config_destroy(cfg);
        return -1;
    }

    /* ui */
    if ((setting = config_lookup(cfg, ui_strings.self)) != NULL) {
        config_setting_lookup_bool(setting, ui_strings.timestamps, &s->timestamps);

        int time = 24;
        if ( config_setting_lookup_int(setting, ui_strings.time_format, &time) ) {
            if (time == 12) {
                snprintf(s->timestamp_format, sizeof(s->timestamp_format), "%s", "%I:%M:%S %p");
                snprintf(s->log_timestamp_format, sizeof(s->log_timestamp_format), "%s", "%Y/%m/%d [%I:%M:%S %p]");
            }
        }

        if ( config_setting_lookup_string(setting, ui_strings.timestamp_format, &str) ) {
            snprintf(s->timestamp_format, sizeof(s->timestamp_format), "%s", str);
        }

        if ( config_setting_lookup_string(setting, ui_strings.log_timestamp_format, &str) ) {
            snprintf(s->log_timestamp_format, sizeof(s->log_timestamp_format), "%s", str);
        }

        config_setting_lookup_bool(setting, ui_strings.alerts, &s->alerts);
        config_setting_lookup_bool(setting, ui_strings.autolog, &s->autolog);
        config_setting_lookup_bool(setting, ui_strings.native_colors, &s->colour_theme);
        config_setting_lookup_int(setting, ui_strings.history_size, &s->history_size);
        config_setting_lookup_bool(setting, ui_strings.show_typing_self, &s->show_typing_self);
        config_setting_lookup_bool(setting, ui_strings.show_typing_other, &s->show_typing_other);
        config_setting_lookup_bool(setting, ui_strings.show_welcome_msg, &s->show_welcome_msg);

        if ( config_setting_lookup_string(setting, ui_strings.line_join, &str) ) {
            snprintf(s->line_join, sizeof(s->line_join), "%s", str);
        }
        if ( config_setting_lookup_string(setting, ui_strings.line_quit, &str) ) {
            snprintf(s->line_quit, sizeof(s->line_quit), "%s", str);
        }
        if ( config_setting_lookup_string(setting, ui_strings.line_alert, &str) ) {
            snprintf(s->line_alert, sizeof(s->line_alert), "%s", str);
        }
        if ( config_setting_lookup_string(setting, ui_strings.line_normal, &str) ) {
            snprintf(s->line_normal, sizeof(s->line_normal), "%s", str);
        }

        config_setting_lookup_bool (setting, ui_strings.mplex_away, &s->mplex_away);

        if (config_setting_lookup_string (setting, ui_strings.mplex_away_note, &str)) {
            snprintf (s->mplex_away_note, sizeof (s->mplex_away_note), "%s", str);
        }
    }

    /* paths */
    if ((setting = config_lookup(cfg, tox_strings.self)) != NULL) {
        if ( config_setting_lookup_string(setting, tox_strings.download_path, &str) ) {
            snprintf(s->download_path, sizeof(s->download_path), "%s", str);
            int len = strlen(s->download_path);

            /* make sure path ends with a '/' */
            if (len >= sizeof(s->download_path) - 2)
                s->download_path[0] = '\0';
            else if (s->download_path[len - 1] != '/')
                strcat(&s->download_path[len - 1], "/");
        }

        if ( config_setting_lookup_string(setting, tox_strings.chatlogs_path, &str) ) {
            snprintf(s->chatlogs_path, sizeof(s->chatlogs_path), "%s", str);
            int len = strlen(s->chatlogs_path);

            if (len >= sizeof(s->chatlogs_path) - 2)
                s->chatlogs_path[0] = '\0';
            else if (s->chatlogs_path[len - 1] != '/')
                strcat(&s->chatlogs_path[len - 1], "/");
        }

        if ( config_setting_lookup_string(setting, tox_strings.avatar_path, &str) ) {
            snprintf(s->avatar_path, sizeof(s->avatar_path), "%s", str);
            int len = strlen(str);

            if (len >= sizeof(s->avatar_path))
                s->avatar_path[0] = '\0';
        }
    }

    /* keys */
    if ((setting = config_lookup(cfg, key_strings.self)) != NULL) {
        const char* tmp = NULL;
        if (config_setting_lookup_string(setting, key_strings.next_tab, &tmp))
            s->key_next_tab = key_parse(&tmp);
        if (config_setting_lookup_string(setting, key_strings.prev_tab, &tmp))
            s->key_prev_tab = key_parse(&tmp);
        if (config_setting_lookup_string(setting, key_strings.scroll_line_up, &tmp))
            s->key_scroll_line_up = key_parse(&tmp);
        if (config_setting_lookup_string(setting, key_strings.scroll_line_down, &tmp))
            s->key_scroll_line_down= key_parse(&tmp);
        if (config_setting_lookup_string(setting, key_strings.half_page_up, &tmp))
            s->key_half_page_up = key_parse(&tmp);
        if (config_setting_lookup_string(setting, key_strings.half_page_down, &tmp))
            s->key_half_page_down = key_parse(&tmp);
        if (config_setting_lookup_string(setting, key_strings.page_bottom, &tmp))
            s->key_page_bottom = key_parse(&tmp);
        if (config_setting_lookup_string(setting, key_strings.peer_list_up, &tmp))
            s->key_peer_list_up = key_parse(&tmp);
        if (config_setting_lookup_string(setting, key_strings.peer_list_down, &tmp))
            s->key_peer_list_down = key_parse(&tmp);
        if (config_setting_lookup_string(setting, key_strings.toggle_peerlist, &tmp))
            s->key_toggle_peerlist = key_parse(&tmp);
    }

#ifdef AUDIO
    if ((setting = config_lookup(cfg, audio_strings.self)) != NULL) {
        config_setting_lookup_int(setting, audio_strings.input_device, &s->audio_in_dev);
        s->audio_in_dev = s->audio_in_dev < 0 || s->audio_in_dev > MAX_DEVICES ? 0 : s->audio_in_dev;

        config_setting_lookup_int(setting, audio_strings.output_device, &s->audio_out_dev);
        s->audio_out_dev = s->audio_out_dev < 0 || s->audio_out_dev > MAX_DEVICES ? 0 : s->audio_out_dev;

        config_setting_lookup_float(setting, audio_strings.VAD_treshold, &s->VAD_treshold);
    }
#endif

#ifdef SOUND_NOTIFY
    if ((setting = config_lookup(cfg, sound_strings.self)) != NULL) {
        if ( (config_setting_lookup_string(setting, sound_strings.notif_error, &str) != CONFIG_TRUE) ||
                !set_sound(notif_error, str) ) {
            if (str && strcasecmp(str, NO_SOUND) != 0)
                set_sound(notif_error, PACKAGE_DATADIR "/sounds/ToxicError.wav");
        }

        if ( !config_setting_lookup_string(setting, sound_strings.user_log_in, &str) ||
                !set_sound(user_log_in, str) ) {
            if (str && strcasecmp(str, NO_SOUND) != 0)
                set_sound(user_log_in, PACKAGE_DATADIR "/sounds/ToxicContactOnline.wav");
        }

        if ( !config_setting_lookup_string(setting, sound_strings.user_log_out, &str) ||
                !set_sound(user_log_out, str) ) {
            if (str && strcasecmp(str, NO_SOUND) != 0)
                set_sound(user_log_out, PACKAGE_DATADIR "/sounds/ToxicContactOffline.wav");
        }

        if ( !config_setting_lookup_string(setting, sound_strings.call_incoming, &str) ||
                !set_sound(call_incoming, str) ) {
            if (str && strcasecmp(str, NO_SOUND) != 0)
                set_sound(call_incoming, PACKAGE_DATADIR "/sounds/ToxicIncomingCall.wav");
        }

        if ( !config_setting_lookup_string(setting, sound_strings.call_outgoing, &str) ||
                !set_sound(call_outgoing, str) ) {
            if (str && strcasecmp(str, NO_SOUND) != 0)
                set_sound(call_outgoing, PACKAGE_DATADIR "/sounds/ToxicOutgoingCall.wav");
        }

        if ( !config_setting_lookup_string(setting, sound_strings.generic_message, &str) ||
                !set_sound(generic_message, str) ) {
            if (str && strcasecmp(str, NO_SOUND) != 0)
                set_sound(generic_message, PACKAGE_DATADIR "/sounds/ToxicRecvMessage.wav");
        }

        if ( !config_setting_lookup_string(setting, sound_strings.transfer_pending, &str) ||
                !set_sound(transfer_pending, str) ) {
            if (str && strcasecmp(str, NO_SOUND) != 0)
                set_sound(transfer_pending, PACKAGE_DATADIR "/sounds/ToxicTransferStart.wav");
        }

        if ( !config_setting_lookup_string(setting, sound_strings.transfer_completed, &str) ||
                !set_sound(transfer_completed, str) ) {
            if (str && strcasecmp(str, NO_SOUND) != 0)
                set_sound(transfer_completed, PACKAGE_DATADIR "/sounds/ToxicTransferComplete.wav");
        }
    }
    else {
        set_sound(notif_error, PACKAGE_DATADIR "/sounds/ToxicError.wav");
        set_sound(user_log_in, PACKAGE_DATADIR "/sounds/ToxicContactOnline.wav");
        set_sound(user_log_out, PACKAGE_DATADIR "/sounds/ToxicContactOffline.wav");
        set_sound(call_incoming, PACKAGE_DATADIR "/sounds/ToxicIncomingCall.wav");
        set_sound(call_outgoing, PACKAGE_DATADIR "/sounds/ToxicOutgoingCall.wav");
        set_sound(generic_message, PACKAGE_DATADIR "/sounds/ToxicRecvMessage.wav");
        set_sound(transfer_pending, PACKAGE_DATADIR "/sounds/ToxicTransferStart.wav");
        set_sound(transfer_completed, PACKAGE_DATADIR "/sounds/ToxicTransferComplete.wav");
    }
#endif

    config_destroy(cfg);
    return 0;
}
예제 #11
0
void SetTrackingParams( ConvUnits* calParams ){

    //init parameters
	config_t cfg;
	config_setting_t *setting;
	char settingName[30];
	char configFile[30];
	char settingFather[30];

	int EXITO;
	int DEFAULT = false;

	// Reservar memoria
	if( !trackParams){
		trackParams = ( TrackingParams *) malloc( sizeof( TrackingParams) );
		if(!trackParams) {error(4); return;}
	}

	fprintf(stderr, "\nCargando parámetros para Tracking...");
	config_init(&cfg);

	sprintf( configFile, "config.cfg");
	sprintf( settingFather,"TrackingParams" );

	 /* Leer archivo. si hay un error, informar y cargar configuración por defecto */
	if(! config_read_file(&cfg, configFile))
	{
		fprintf(stderr, "%s:%d - %s\n", config_error_file(&cfg),
				config_error_line(&cfg), config_error_text(&cfg));

		fprintf(stderr, "Error al acceder al fichero de configuración %s .\n"
						" Estableciendo valores por defecto.\n"
						,configFile);
		DEFAULT = true;
	}
	else
	{
		setting = config_lookup(&cfg, settingFather);
		/* Si no se se encuentra la setting o bien existe la variable hijo Auto y ésta es true, se establecen TODOS los valores por defecto.*/
		if(setting != NULL)
		{
			sprintf(settingName,"Auto");
			/* Obtener el valor */
			EXITO = config_setting_lookup_bool ( setting, settingName, &DEFAULT);
			if(!EXITO) DEFAULT = true;
			else if( EXITO && DEFAULT ) fprintf(stderr, "\n Opción Auto activada para el campo %s.\n"
												" Estableciendo valores por defecto.\n",settingFather);
			else if( EXITO && !DEFAULT) fprintf(stderr, "\n Opción Auto desactivada para el campo %s.\n"
												" Estableciendo valores del fichero de configuración.\n",settingFather);
		}
		else {
			DEFAULT = true;
			fprintf(stderr, "Error.No se ha podido leer el campo %s.\n"
							" Estableciendo valores por defecto.\n",settingFather);
		}
	}

	if( DEFAULT ) SetDefaultTrackParams(  );
	/* Valores leídos del fichero de configuración. Algunos valores puedes ser establecidos por defecto si se indica
	 * expresamente en el fichero de configuración. Si el valor es erroneo o no se encuentra la variable, se establecerán
	 * a los valores por defecto.
	 */
	else{
		double val;
		 /* Get the store name. */
		sprintf(settingName,"MaxBlobs");
		if(! config_setting_lookup_int ( setting, settingName, &trackParams->MaxBlobs )  ){
			trackParams->MaxBlobs = 10;
			fprintf(stderr, "No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
							"Establecer por defecto a %d \n",settingName,trackParams->MaxBlobs );

		}

		sprintf(settingName,"ShowKalmanData");
				if(! config_setting_lookup_bool ( setting, settingName, &trackParams->ShowKalmanData )  ){
					trackParams->ShowKalmanData = false;
					fprintf(stderr, "No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
									"Establecer por defecto a %d \n",settingName,trackParams->ShowKalmanData );

		}

		sprintf(settingName,"MaxTimeSlept");
		if(! config_setting_lookup_int ( setting, settingName, &trackParams->MaxTimeSlept  )  ){
			trackParams->MaxTimeSlept = 200;
			fprintf(stderr, "No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
							"Establecer por defecto a %d \n",settingName,trackParams->MaxTimeSlept );

		}

		sprintf(settingName,"MaxBuffer");
		if(! config_setting_lookup_int ( setting, settingName, &trackParams->MaxBuffer )  ){
			trackParams->MaxBuffer = 50;
			fprintf(stderr, "No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
							"Establecer por defecto a %d \n",settingName,trackParams->MaxBuffer);
		}

		sprintf(settingName,"NumberOfIdentities");
		if(! config_setting_lookup_int ( setting, settingName, &trackParams->NumberOfIdentities )  ){
			trackParams->NumberOfIdentities = 100;
			fprintf(stderr, "No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
							"Establecer por defecto a %d \n",settingName,trackParams->NumberOfIdentities);
		}

		sprintf(settingName, "PeriodoVelMed");
		if (!config_setting_lookup_float(setting, settingName,
				&val)) {
			trackParams->PeriodoVelMed = 60;
			fprintf(
					stderr,
					"No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
						"Establecer por defecto a %d frames\n",
					settingName, trackParams->PeriodoVelMed);

		} else if(!val	|| val < 0 ){

				trackParams->PeriodoVelMed = 60;
				fprintf(stderr,
						"El valor de %s está fuera de límites\n "
							"Establecer por defecto %s a %d frames \n",
						settingName, settingName,
						trackParams->PeriodoVelMed);
		}
		else{
			trackParams->PeriodoVelMed = cvRound( (float)val * calParams->FPS); // a frames
		}

		sprintf(settingName,"MediumActivityTh");
		if(! config_setting_lookup_float ( setting, settingName, &trackParams->MediumActivityTh )  ){
			trackParams->MediumActivityTh	= 2.0 ;
			fprintf(stderr, "No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
							"Establecer por defecto a %0.1f \n",settingName,trackParams->MediumActivityTh);

		}

		sprintf(settingName,"LowActivityTh");
		if(! config_setting_lookup_float ( setting, settingName, &trackParams->LowActivityTh )  ){
			trackParams->LowActivityTh	= 0.5 ;
			fprintf(stderr, "No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
							"Establecer por defecto a %0.1f \n",settingName,trackParams->LowActivityTh);

		}

		sprintf(settingName,"NullActivityTh");
		if(! config_setting_lookup_float ( setting, settingName, &trackParams->NullActivityTh )  ){
			trackParams->NullActivityTh	= 0.2 ;
			fprintf(stderr, "No se encuentra la variable %s en el archivo de configuración o el tipo de dato es incorrecto.\n "
							"Establecer por defecto a %0.1f \n",settingName,trackParams->NullActivityTh);
		}

	}

	SetPrivateTrackParams( calParams );
	ShowTrackParams( settingFather );
	SetKalmanFilterParams( trackParams );

	config_destroy(&cfg);
}
예제 #12
0
파일: options.cpp 프로젝트: rdewaele/adhd
// TODO: stop abusing NAME_MAX ;-)
// TODO: proper bounds checking for all types
static void config2options(const config_t * config, struct Options * options) {

	// generic group
	struct Options_generic gn_opt;
	{
		double frequency;
		int logging, silent;
		char logfile[NAME_MAX], create[NAME_MAX];
		long long processes_begin, processes_end, threads_begin, threads_end;

		config_setting_t * generic = config_lookup(config, FLD_GENERIC_GROUP);
		config_setting_lookup_float(generic, FLD_GENERIC_GPU_FREQUENCY, &frequency);
		config_setting_lookup_bool(generic, FLD_GENERIC_LOGGING, &logging);
		c2o_strncpy(logfile,
				config_setting_get_member(generic, FLD_GENERIC_LOGFILE), NAME_MAX);
		c2o_strncpy(create,
				config_setting_get_member(generic, FLD_GENERIC_SPAWN), NAME_MAX);
		config_setting_lookup_int64(generic, FLD_GENERIC_PROCESSES_BEGIN, &processes_begin);
		config_setting_lookup_int64(generic, FLD_GENERIC_PROCESSES_END, &processes_end);
		config_setting_lookup_int64(generic, FLD_GENERIC_THREADS_BEGIN, &threads_begin);
		config_setting_lookup_int64(generic, FLD_GENERIC_THREADS_END, &threads_end);
		config_setting_lookup_bool(generic, FLD_GENERIC_SILENT, &silent);

		gn_opt = Options_generic {
			spawn_typeFromString(create),
				frequency,
				(bool)logging,
				"", // XXX strncpy ! (log filename)
				(unsigned)processes_begin,
				(unsigned)processes_end,
				(bool)silent,
				(unsigned)threads_begin,
				(unsigned)threads_end
		};
		strncpy(gn_opt.csvlogname, logfile, NAME_MAX);
	}

	// walking array group
	struct Options_walkarray wa_opt;
	{
		long long aaccesses, begin, repetitions, end, step;
		char scaling[NAME_MAX], pattern[NAME_MAX];

		config_setting_t * array = config_lookup(config, FLD_WALKARRAY_GROUP);
		config_setting_lookup_int64(array, FLD_WALKARRAY_ACCESSES, &aaccesses);
		config_setting_lookup_int64(array, FLD_WALKARRAY_REPEAT, &repetitions);
		config_setting_lookup_int64(array, FLD_WALKARRAY_BEGINLENGTH, &begin);
		config_setting_lookup_int64(array, FLD_WALKARRAY_ENDLENGTH, &end);
		config_setting_lookup_int64(array, FLD_WALKARRAY_INCREMENT, &step);
		c2o_strncpy(scaling,
				config_setting_get_member(array, FLD_WALKARRAY_SCALING), NAME_MAX);
		c2o_strncpy(pattern,
				config_setting_get_member(array, FLD_WALKARRAY_PATTERN), NAME_MAX);

		wa_opt = Options_walkarray {
			(unsigned)aaccesses,
				(walking_t)begin,
				(walking_t)end,
				pattern_typeFromString(pattern),
				(unsigned)repetitions,
				(walking_t)step
		};
	}

	// streaming array group
	struct Options_streamarray sa_opt;
	{
		long long begin, end, step;
		char scaling[NAME_MAX];

		config_setting_t * array = config_lookup(config, FLD_STREAMARRAY_GROUP);
		config_setting_lookup_int64(array, FLD_STREAMARRAY_BEGINLENGTH, &begin);
		config_setting_lookup_int64(array, FLD_STREAMARRAY_ENDLENGTH, &end);
		config_setting_lookup_int64(array, FLD_STREAMARRAY_INCREMENT, &step);
		c2o_strncpy(scaling,
				config_setting_get_member(array, FLD_STREAMARRAY_SCALING), NAME_MAX);

		sa_opt = Options_streamarray {
			(unsigned)begin,
				(unsigned)end,
				(unsigned)step
		};
	}

	// flops array group
	struct Options_flopsarray fa_opt;
	{
		long long begin, end, step, calculations;
		char scaling[NAME_MAX];

		config_setting_t * array = config_lookup(config, FLD_FLOPSARRAY_GROUP);
		config_setting_lookup_int64(array, FLD_FLOPSARRAY_BEGINLENGTH, &begin);
		config_setting_lookup_int64(array, FLD_FLOPSARRAY_ENDLENGTH, &end);
		config_setting_lookup_int64(array, FLD_FLOPSARRAY_INCREMENT, &step);
		config_setting_lookup_int64(array, FLD_FLOPSARRAY_CALCULATIONS, &calculations);
		c2o_strncpy(scaling,
				config_setting_get_member(array, FLD_FLOPSARRAY_SCALING), NAME_MAX);

		fa_opt = Options_flopsarray {
			(unsigned)begin,
				(unsigned)end,
				(unsigned long long)calculations,
				(unsigned)step
		};
	}

	options->generic = gn_opt;
	options->walkArray = wa_opt;
	options->streamArray = sa_opt;
	options->flopsArray = fa_opt;
}
예제 #13
0
int parse_config(char *config_file) {
	config_t config;
	int ret = -1;
	config_setting_t *rtdal,*dac;
	const char *tmp;
	int single_timer;
	int time_slot_us;

	config_init(&config);
	if (!config_read_file(&config, config_file)) {
		aerror_msg("line %d - %s: \n", config_error_line(&config),
				config_error_text(&config));
		goto destroy;
	}

	rtdal = config_lookup(&config, "rtdal");
	if (!rtdal) {
		aerror("Error parsing config file: rtdal section not found.\n");
		goto destroy;
	}

	if (!config_setting_lookup_int(rtdal, "time_slot_us", &time_slot_us)) {
		aerror("time_slot_us field not defined\n");
		goto destroy;
	}

	if (!config_setting_lookup_string(rtdal, "cores", &tmp)) {
		aerror("cores field not defined\n");
		goto destroy;
	}
	nof_cores = parse_cores((char*) tmp);
	if (nof_cores < 0) {
		printf("Error invalid cores %s\n",tmp);
		exit(0);
	}

	if (!config_setting_lookup_bool(rtdal, "enable_usrp", &using_uhd)) {
		aerror("enable_usrp field not defined\n");
		goto destroy;
	}

	if (!config_setting_lookup_bool(rtdal, "timer_mode_single", &single_timer)) {
		aerror("timer_mode_single field not defined\n");
		goto destroy;
	}
	if (using_uhd) {
		if (single_timer) {
			clock_source = SINGLE_TIMER;
		} else {
			clock_source = DAC;
		}
	} else {
		if (single_timer) {
			clock_source = SINGLE_TIMER;
		} else {
			clock_source = MULTI_TIMER;
		}
	}
	if (!config_setting_lookup_string(rtdal, "path_to_libs", &tmp)) {
		aerror("path_to_libs field not defined\n");
		goto destroy;
	}

	strcpy(libs_path,tmp);

	if (using_uhd) {
		dac = config_lookup(&config, "dac");
		if (!dac) {
			aerror("Error parsing config file: dac section not found.\n");
			goto destroy;
		}

#ifdef HAVE_UHD
		double tmp;
		if (!config_setting_lookup_float(dac, "samp_freq", &dac_cfg.inputFreq)) {
			aerror("samp_freq field not defined\n");
			goto destroy;
		}
		dac_cfg.outputFreq = dac_cfg.inputFreq;

		if (!config_setting_lookup_float(dac, "rf_freq", &dac_cfg.inputRFFreq)) {
			aerror("rf_freq field not defined\n");
			goto destroy;
		}
		dac_cfg.outputRFFreq = dac_cfg.inputRFFreq;

		if (!config_setting_lookup_float(dac, "rf_gain", &tmp)) {
			aerror("rf_gain field not defined\n");
			goto destroy;
		}
		dac_cfg.tx_gain = tmp;
		dac_cfg.rx_gain = tmp;

		if (!config_setting_lookup_float(dac, "if_bw", &tmp)) {
			aerror("rf_gain field not defined\n");
			goto destroy;
		}
		dac_cfg.tx_bw = tmp;
		dac_cfg.rx_bw = tmp;

		if (!config_setting_lookup_bool(dac, "sample_is_short", &dac_cfg.sampleType)) {
			aerror("rf_gain field not defined\n");
			goto destroy;
		}

		if (!config_setting_lookup_int(dac, "block_size", &dac_cfg.NsamplesIn)) {
			aerror("block_size field not defined\n");
			goto destroy;
		}
		dac_cfg.NsamplesOut = dac_cfg.NsamplesIn;

		if (!config_setting_lookup_bool(dac, "chain_is_tx", &dac_cfg.chain_is_tx)) {
			aerror("chain_is_tx field not defined\n");
			goto destroy;
		}

		dac_cfg.sampleType = 0;
		dac_cfg.nof_channels = 1;

		uhd_readcfg(&dac_cfg);
#endif
	}
	if (using_uhd) {
#ifdef HAVE_UHD
		timeslot_us = (long int) 1000000*((float) dac_cfg.NsamplesOut/dac_cfg.outputFreq);
#endif
	} else {
		timeslot_us = time_slot_us;
	}
	ret=0;
destroy:
	config_destroy(&config);
	return ret;
}