Ejemplo n.º 1
0
static int
printf_flag_info (struct printf_info *const pinfo, size_t n, int *argtypes)
{
  return_val_if_fail (pinfo != NULL, SNV_ERROR);

  if (!(pinfo->state & (SNV_STATE_BEGIN | SNV_STATE_FLAG)))
    {
      PRINTF_ERROR (pinfo, "invalid specifier");
      return -1;
    }

  pinfo->state = SNV_STATE_FLAG;

  while (pinfo->state & SNV_STATE_FLAG)
    {
      switch (*pinfo->format)
	{
	case '#':
	  pinfo->alt = TRUE;
	  pinfo->format++;
	  break;

	case '0':
	  if (!pinfo->left)
	    pinfo->pad = '0';
	  pinfo->format++;
	  break;

	case '-':
	  pinfo->pad = ' ';
	  pinfo->left = TRUE;
	  pinfo->format++;
	  break;

	case ' ':
	  pinfo->space = TRUE;
	  pinfo->format++;
	  break;

	case '+':
	  pinfo->showsign = TRUE;
	  pinfo->format++;
	  break;

	case '\'':
	  pinfo->group = TRUE;
	  pinfo->format++;
	  break;

	default:
	  pinfo->state = ~(SNV_STATE_BEGIN | SNV_STATE_FLAG);
	  break;
	}
    }

  pinfo->format--;

  /* Return the number of characters emitted. */
  return 0;
}
Ejemplo n.º 2
0
static int
printf_string (STREAM *stream, struct printf_info *const pinfo, union printf_arg const *args)
{
  int len = 0, count_or_errorcode = SNV_OK;
  const char *p = NULL;

  return_val_if_fail (pinfo != NULL, SNV_ERROR);

  /* Read these now to advance the argument pointer appropriately */
  if (pinfo->prec == -1)
    pinfo->prec = 0;

  /* Check for valid pre-state. */
  if (pinfo->prec <= -1
     || pinfo->is_char || pinfo->is_short || pinfo->is_long
     || pinfo->is_long_double)
    {
      PRINTF_ERROR (pinfo, "invalid flags");
      return -1;
    }

  /* Extract the correct argument from the arg vector. */
  p = args->pa_string;

  /* Left pad to the width if the supplied argument is less than
     the width specifier.  */
  if (p != NULL)
    {
      len = strlen (p);
      if (pinfo->prec && pinfo->prec < len)
	len = pinfo->prec;
    }

  if ((len < pinfo->width) && !pinfo->left)
    {
      int padwidth = pinfo->width - len;
      while ((count_or_errorcode >= 0) && (count_or_errorcode < padwidth))
	SNV_EMIT (pinfo->pad, stream, count_or_errorcode);
    }

  /* Fill the buffer with as many characters from the format argument
     as possible without overflowing or exceeding the precision.  */
  if ((count_or_errorcode >= 0) && (p != NULL))
    {
      int mark = count_or_errorcode;
      while ((count_or_errorcode >= 0) && *p != '\0'
	     && ((pinfo->prec == 0) || (count_or_errorcode - mark < len)))
	SNV_EMIT (*p++, stream, count_or_errorcode);
    }

  /* Right pad to the width if we still didn't reach the specified
     width and the left justify flag was set.  */
  if ((count_or_errorcode < pinfo->width) && pinfo->left)
    while ((count_or_errorcode >= 0)
	   && (count_or_errorcode < pinfo->width))
      SNV_EMIT (pinfo->pad, stream, count_or_errorcode);

  /* Return the number of characters emitted. */
  return count_or_errorcode;
}
Ejemplo n.º 3
0
static int
printf_pointer (STREAM *stream, struct printf_info *const pinfo, union printf_arg const *args)
{
  int count_or_errorcode = SNV_OK;

  return_val_if_fail (pinfo != NULL, SNV_ERROR);

  /* Read these now to advance the argument pointer appropriately */
  if (pinfo->prec == -1)
    pinfo->prec = 0;

  /* Check for valid pre-state. */
  if (pinfo->prec <= -1
     || pinfo->is_char || pinfo->is_short || pinfo->is_long
     || pinfo->is_long_double)
    {
      PRINTF_ERROR (pinfo, "invalid flags");
      return -1;
    }

  /* Always print 0x. */
  pinfo->alt = 1;
  pinfo->is_long = sizeof(long) == sizeof (char *);
  pinfo->is_long_double = sizeof(intmax_t) == sizeof (char *);

  /* Use the standard routine for numbers for the printing call,
     if the pointer is not NULL.  */

  if (args->pa_pointer != NULL)
    return printf_integer (stream, pinfo, args);

  /* Print a NULL pointer as (nil), appropriately padded.  */
  if ((pinfo->width > 5) && !pinfo->left)
    {
      int padwidth = pinfo->width - 5;
      while ((count_or_errorcode >= 0) && (count_or_errorcode < padwidth))
	SNV_EMIT (pinfo->pad, stream, count_or_errorcode);
    }

  SNV_EMIT ('(', stream, count_or_errorcode);
  SNV_EMIT ('n', stream, count_or_errorcode);
  SNV_EMIT ('i', stream, count_or_errorcode);
  SNV_EMIT ('l', stream, count_or_errorcode);
  SNV_EMIT (')', stream, count_or_errorcode);

  if ((pinfo->width > 5) && pinfo->left)
    while ((count_or_errorcode >= 0)
	   && (count_or_errorcode < pinfo->width))
      SNV_EMIT (pinfo->pad, stream, count_or_errorcode);

  return count_or_errorcode;
}
Ejemplo n.º 4
0
static int
printf_char (STREAM *stream, struct printf_info *const pinfo, union printf_arg const *args)
{
  int count_or_errorcode = SNV_OK;
  char ch = '\0';

  return_val_if_fail (pinfo != NULL, SNV_ERROR);

  /* Check for valid pre-state. */
  if (pinfo->prec != -1
     || pinfo->is_char || pinfo->is_short || pinfo->is_long
     || pinfo->is_long_double || pinfo->pad == '0'
     || pinfo->alt || pinfo->space || pinfo->showsign)
    {
      PRINTF_ERROR (pinfo, "invalid flags");
      return -1;
    }

  /* Extract the correct argument from the arg vector. */
  ch = args->pa_char;

  /* Left pad to the width if the supplied argument is less than
     the width specifier.  */
  if ((pinfo->width > 1) && !pinfo->left)
    {
      int padwidth = pinfo->width - 1;

      while ((count_or_errorcode >= 0) && (count_or_errorcode < padwidth))
	SNV_EMIT (pinfo->pad, stream, count_or_errorcode);
    }

  /* Emit the character argument.  */
  SNV_EMIT (ch, stream, count_or_errorcode);

  /* Right pad to the width if we still didn't reach the specified
     width and the left justify flag was set.  */
  if ((count_or_errorcode < pinfo->width) && pinfo->left)
    while ((count_or_errorcode >= 0)
	   && (count_or_errorcode < pinfo->width))
      SNV_EMIT (pinfo->pad, stream, count_or_errorcode);

  /* Return the number of characters emitted. */
  return count_or_errorcode;
}
Ejemplo n.º 5
0
Archivo: netdrv.c Proyecto: ariavie/bcm
/**
 *
 * NetdrvMemInit - initialize memory for the chip
 *
 * This routine is highly specific to the device.
 *
 * Input: device to be initialized
 * RETURNS: OK or ERROR.
 *
 *
 **/
STATUS
NetdrvMemInit(END_DEVICE * pDrvCtrl)
{
    

    /*
     * This is how we would set up and END netPool using netBufLib(1).
     * This code is pretty generic.
     */
    if(pDrvCtrl == NULL)
        return ERROR;

    if((pDrvCtrl->end.pNetPool = malloc (sizeof(NET_POOL))) == NULL)
        return (ERROR);

    NetdrvMclBlkConfig.mBlkNum = 1024 /*32*/;
    NetdrvClDescTbl[0].clNum = 512 /* 1MB */;
    NetdrvMclBlkConfig.clBlkNum = NetdrvClDescTbl[0].clNum;

    /* Calculate the total memory for all the M-Blks and CL-Blks. */
    NetdrvMclBlkConfig.memSize =
        (NetdrvMclBlkConfig.mBlkNum * (MSIZE + sizeof (int))) +
        (NetdrvMclBlkConfig.clBlkNum * (CL_BLK_SZ));

    NetdrvMclBlkConfig.memArea =
        (char *) memalign (4, (UINT) NetdrvMclBlkConfig.memSize);

    if(NetdrvMclBlkConfig.memArea == NULL)
        return (ERROR);

    /* Calculate the memory size of all the clusters. */
    NetdrvClDescTbl[0].memSize = (NetdrvClDescTbl[0].clNum *
        (NetdrvClDescTbl[0].clSize + sizeof(int)));

    /* Allocate the memory for the clusters from cache safe memory. */
    NetdrvClDescTbl[0].memArea =
        (char *) sal_dma_alloc(NetdrvClDescTbl[0].memSize, "mema");

    if (NetdrvClDescTbl[0].memArea == NULL) {
        PRINTF_ERROR(("\r\nsystem memory unavailable!"));
        return (ERROR);
    }

    /* Initialize the memory pool. */
    if (netPoolInit(pDrvCtrl->end.pNetPool, &NetdrvMclBlkConfig,
        &NetdrvClDescTbl[0], NetdrvClDescTblNumEnt, NULL) == ERROR) {
        PRINTF_ERROR(("\r\nCould not init buffering"));
        return (ERROR);
    }

    /*
     * If you need clusters to store received packets into then get them
     * here ahead of time.
     */
    if ((pDrvCtrl->pClPoolId =
        netClPoolIdGet (pDrvCtrl->end.pNetPool, sizeof (RFD), FALSE)) == NULL) {
        return (ERROR);
    }

    PRINTF_DEBUG(("\r\nMemory setup complete"));

    return OK;
}
Ejemplo n.º 6
0
int query_result_to_cstring(const char* path, char res_string[], size_t size, ngx_http_request_t *r)
{
    int ret = 0;
    res_string[0] = '\0';

    static MYSQL *kconn = NULL;
    static int kconnected = 0;
    static int kconnect_times = 0;
    static int kquery_times = 0;

    if(!kconnected) {
        kconnect_times ++;

        char server[] = "localhost";
        char user[] = "root";
        char password[] = "mysql@ubuntu";
        char database[] = "notetask";
    
        kconn = mysql_init(NULL);
    
        if (!mysql_real_connect(kconn, server,user, password, database, 0, NULL, 0)) {
            PRINTF_ERROR("mysql connect error : %s\n", mysql_error(kconn));
            mysql_close(kconn);
            mysql_library_end();
            kconn = NULL;
            kconnected = 0;
            ret = -1;
            goto finish;
        }
            else {
            PRINTF_DEBUG("mysql connect OK [%d].\n", getpid());
            kconnected = 1;
            }
    }

    //根据请求的path, 组合查询语句.
    #define LEN_QUERY_STRING (1024)
    char query_string[LEN_QUERY_STRING];
    snprintf(query_string, LEN_QUERY_STRING, "%s", "select * from notetask"); 

    int ret_query = mysql_query(kconn, query_string);
    kquery_times ++;
    if(ret_query) {
        PRINTF_ERROR("mysql query error : %s\n", mysql_error(kconn));
        mysql_close(kconn);
        mysql_library_end();
        kconn = NULL;
        kconnected = 0;
        ret = -1;
        goto finish;
    }

    MYSQL_ROW sqlrow;
    MYSQL_RES *res_ptr;

    size_t len = 0;

    res_ptr = mysql_store_result(kconn);

    int64_t uid = 100;
    int type = 1;
    int count = 18;
    int version = 667;
    int status = 0;

    const char* title = "当前任务";
    int page = 1;
    int code = 200;
    int success = 1;
    const char* message = "";
    len += snprintf(res_string, size-len, 
            "{"
                "\"notetasks\":{"
                    "\"uid\":%"PRIu64","
                    "\"type\":%d,"
                    "\"count\":%d,"
                    "\"version\":%d,"
                    "\"server\":\"%d.%d.%d.%d\","
                    "\"status\":%d"
                "},"
                "\"page\":{"
                    "\"title\":\"%s\","
                    "\"page\":%d"
                "},"
                "\"code\":%d,"
                "\"success\":%s,"
                "\"message\":\"%s\","
                "\"notes\":[", 
                    uid,
                    type,
                    count,
                    version,
                    ngx_getpid(), ngx_log_tid, kconnect_times, kquery_times,
                    status,
                    title, 
                    page,
                    code,
                    success?"true":"false",
                    message);

    int row_number = 0;

    if(res_ptr) {
        while((sqlrow = mysql_fetch_row(res_ptr)) && len + 1 < size) {

            row_number ++;

            len += snprintf(res_string + len, size - len, 
                    "%s{"
                        "\"uid\":%s," 
                        "\"status\":%s," 
                        "\"startDateTime\":\"%s\"," 
                        "\"finishDateTime\":\"%s\"," 
                        "\"commitDateTime\":\"%s\"," 
                        "\"updateDateTime\":\"%s\"," 
                        "\"content\":\"%s\","
                        "\"isShared\":%s,"
                        "\"isOnlyLocal\":%s,"
                        "\"isOnlyWorkday\":%s,"
                        "\"isDailyRepeat\":%s,"
                        "\"isWeeklyRepeat\":%s,"
                        "\"isYearlyRepeat\":%s,"
                        "\"commentNumber\":%ld,"
                        "\"likeNumber\":%ld"
                    "}", 
                    row_number > 1 ? "," : "", 
                    sqlrow[1],
                    sqlrow[2],
                    sqlrow[3],
                    sqlrow[4],
                    sqlrow[5],
                    sqlrow[6],
                    sqlrow[7],
                    sqlrow[8],
                    sqlrow[9],
                    sqlrow[10],
                    sqlrow[11],
                    sqlrow[12],
                    sqlrow[13],
                    atol(sqlrow[14]),
                    atol(sqlrow[15])
                        );
        }

        if(len+1 < size) {
            len += snprintf(res_string + len, size - len, 
                "]"
                "}");
        }

        mysql_free_result(res_ptr);
        res_ptr = NULL;
    }
    else {
        PRINTF_ERROR("mysql_use_result error : %s.\n", mysql_error(kconn));
        mysql_close(kconn);
        mysql_library_end();
        kconn = NULL;
        kconnected = 0;
        ret = -1;
        goto finish;
    }

finish:
    return ret;
}
Ejemplo n.º 7
0
/**
 * printf_generic:
 * @stream: the stream (possibly a struct printfv_stream appropriately
 * cast) on which to write output.
 * @pinfo: the current state information for the format string parser.
 * @args: the pointer to the first argument to be read by the handler
 *
 * An example implementation of a %printf_function, used to provide easy
 * access to justification, width and precision options.
 *
 * Return value:
 * The number of characters output.
 **/
int
printf_generic (STREAM *stream, struct printf_info *const pinfo, union printf_arg const *args)
{
  int len = 0, count_or_errorcode = SNV_OK;
  char *p = NULL;

  /* Used to interface to the custom function. */
  STREAM *out;
  Filament *fil;
  printf_function *user_func = (printf_function *) pinfo->extra;

  return_val_if_fail (pinfo != NULL, SNV_ERROR);

  /* Read these now to advance the argument pointer appropriately */
  if (pinfo->prec == -1)
    pinfo->prec = 0;

  /* Check for valid pre-state. */
  if (pinfo->prec <= -1)
    {
      PRINTF_ERROR (pinfo, "invalid flags");
      return -1;
    }

  /* Print to a stream using a user-supplied function. */
  fil = filnew (NULL, (size_t)0);
  out = stream_new (fil, SNV_UNLIMITED, NULL, snv_filputc);
  user_func (out, pinfo, args);
  stream_delete (out);
  len = (int)fillen (fil);
  p = fildelete (fil);

  /* Left pad to the width if the supplied argument is less than
     the width specifier.  */
  if (p != NULL && pinfo->prec && pinfo->prec < len)
    len = pinfo->prec;

  if ((len < pinfo->width) && !pinfo->left)
    {
      int padwidth = pinfo->width - len;
      while ((count_or_errorcode >= 0) && (count_or_errorcode < padwidth))
	SNV_EMIT (pinfo->pad, stream, count_or_errorcode);
    }

  /* Fill the buffer with as many characters from the format argument
   * as possible without overflowing or exceeding the precision.
   */
  if ((count_or_errorcode >= 0) && (p != NULL))
    {
      int mark = count_or_errorcode;
      while ((count_or_errorcode >= 0) && *p != '\0'
	     && ((pinfo->prec == 0) || (count_or_errorcode - mark < len)))
	SNV_EMIT (*p++, stream, count_or_errorcode);
    }

  /* Right pad to the width if we still didn't reach the specified
   * width and the left justify flag was set.
   */
  if ((count_or_errorcode < pinfo->width) && pinfo->left)
    while ((count_or_errorcode >= 0)
	   && (count_or_errorcode < pinfo->width))
      SNV_EMIT (pinfo->pad, stream, count_or_errorcode);

  /* Return the number of characters emitted. */
  return count_or_errorcode;
}
Ejemplo n.º 8
0
static struct usb_device_info * usb_device_is_valid(struct libusb_device * dev) {

	int err, i;
	char product[1024];
	libusb_device_handle * udev;
	struct usb_device_info * ret = NULL;
	struct libusb_device_descriptor desc;

	if ( libusb_get_device_descriptor(dev, &desc) < 0 ) {
		PRINTF_LINE("libusb_get_device_descriptor failed");
		PRINTF_END();
		return NULL;
	}

	for ( i = 0; usb_devices[i].vendor; ++i ) {

		if ( desc.idVendor == usb_devices[i].vendor && desc.idProduct == usb_devices[i].product ) {

			printf("\b\b  ");
			PRINTF_END();
			PRINTF_ADD("Found ");
			usb_flash_device_info_print(&usb_devices[i]);
			PRINTF_END();

			PRINTF_LINE("Opening USB...");

			err = libusb_open(dev, &udev);
			if ( err < 0 ) {
				PRINTF_ERROR("libusb_open failed");
				fprintf(stderr, "\n");
				return NULL;
			}

			usb_descriptor_info_print(udev, dev, product, sizeof(product));

			if ( usb_devices[i].interface >= 0 ) {

				PRINTF_LINE("Detaching kernel from USB interface...");
				libusb_detach_kernel_driver(udev, usb_devices[i].interface);

				PRINTF_LINE("Claiming USB interface...");
				if ( libusb_claim_interface(udev, usb_devices[i].interface) < 0 ) {
					PRINTF_ERROR("libusb_claim_interface failed");
					fprintf(stderr, "\n");
					usb_reattach_kernel_driver(udev, usb_devices[i].interface);
					libusb_close(udev);
					return NULL;
				}

			}

			if ( usb_devices[i].alternate >= 0 ) {
				PRINTF_LINE("Setting alternate USB interface...");
				if ( libusb_set_interface_alt_setting(udev, usb_devices[i].interface, usb_devices[i].alternate) < 0 ) {
					PRINTF_ERROR("libusb_claim_interface failed");
					fprintf(stderr, "\n");
					usb_reattach_kernel_driver(udev, usb_devices[i].interface);
					libusb_close(udev);
					return NULL;
				}
			}

			if ( usb_devices[i].configuration >= 0 ) {
				PRINTF_LINE("Setting USB configuration...");
				if ( libusb_set_configuration(udev, usb_devices[i].configuration) < 0 ) {
					PRINTF_ERROR("libusb_set_configuration failed");
					fprintf(stderr, "\n");
					usb_reattach_kernel_driver(udev, usb_devices[i].interface);
					libusb_close(udev);
					return NULL;
				}
			}

			ret = calloc(1, sizeof(struct usb_device_info));
			if ( ! ret ) {
				ALLOC_ERROR();
				usb_reattach_kernel_driver(udev, usb_devices[i].interface);
				libusb_close(udev);
				return NULL;
			}

			if ( strstr(product, "N900") )
				ret->device = DEVICE_RX_51;
			else if ( strstr(product, "N950") )
				ret->device = DEVICE_RM_680;
			else
				ret->device = DEVICE_UNKNOWN;

			/* TODO: Autodetect more devices */

			if ( device_to_string(ret->device) )
				PRINTF_LINE("Detected USB device: %s", device_to_string(ret->device));
			else
				PRINTF_LINE("Detected USB device: (not detected)");
			PRINTF_END();

			if ( ret->device ) {
				enum device * device;
				for ( device = usb_devices[i].devices; *device; ++device )
					if ( *device == ret->device )
						break;
				if ( ! *device ) {
					ERROR("Device mishmash");
					fprintf(stderr, "\n");
					usb_reattach_kernel_driver(udev, usb_devices[i].interface);
					libusb_close(udev);
					free(ret);
					return NULL;
				}
			}

			ret->hwrev = -1;
			ret->flash_device = &usb_devices[i];
			ret->udev = udev;
			break;
		}
	}

	return ret;

}
AUSceneMap::AUSceneMap(const SI32 iEscena, IListenerScenes* scenes) : AUAppEscena(){
	NB_DEFINE_NOMBRE_PUNTERO(this, "AUSceneMap")
	_iScene		= iEscena;
	_scenes			= scenes;
	_animObjects	= new(this) AUAnimadorObjetoEscena();
	//
	_layerScene		= new(this) AUEscenaContenedor();
	_layerGUI		= new(this) AUEscenaContenedor();
	//
	_layerMap		= new(this) AUEscenaContenedor();
	_layerScene->agregarObjetoEscena(_layerMap);
	//Touch layer
	{
		_layerGUITouch			= new(this) AUEscenaContenedor();
		_layerGUITouch->establecerEscuchadorTouches(this, this);
		{
			AUEscenaSprite* touchSprite = NULL;
			touchSprite			= new(this)AUEscenaSprite(); _layerGUITouch->agregarObjetoEscena(touchSprite); touchSprite->liberar();
			touchSprite			= new(this)AUEscenaSprite(); _layerGUITouch->agregarObjetoEscena(touchSprite); touchSprite->liberar();
		}
		_layerGUI->agregarObjetoEscena(_layerGUITouch);
	}
	//
	_routesVisual	= new(this) AUArregloNativoOrdenadoMutableP<STSceneMapRoute>();
	_waysVisual		= new(this) AUArregloNativoOrdenadoMutableP<STSceneMapWay>();
	_nodesVisual	= new(this) AUArregloNativoOrdenadoMutableP<STSceneMapNode>();
	//
	_routesDb		= new(this) AUOsmDatabase();
	if(!_routesDb->loadFromFileXml("./rutasManagua.xml")){
		PRINTF_ERROR("Couldn load osm-xml-file.\n");
	} else {
		PRINTF_INFO("Success, osm-xml-file loaded.\n");
		//
		const AUArregloNativoOrdenadoP<STOsmDbNode>* nodes		= _routesDb->getNodes();
		const AUArregloNativoOrdenadoP<STOsmDbWay>* ways		= _routesDb->getWays();
		const AUArregloNativoOrdenadoP<STOsmDbRoute>* routes	= _routesDb->getRoutes();
		//Load nodes as visual objects
		/*{
			SI32 i; const SI32 count = nodes->conteo;
			for(i = 0; i < count; i++){
				const STOsmDbNode* node = nodes->elemPtr(i);
				STSceneMapNode newNode;
				STSceneMapNode_init(&newNode, this);
				newNode.id = node->id;
				newNode.marker->establecerTraslacion(node->lon * MAP_SCALE, node->lat * MAP_SCALE);
				_layerMap->agregarObjetoEscena(newNode.layer);
				_nodesVisual->agregarElemento(newNode);
			}
		}*/
		//Load ways as visual objects
		{
			SI32 i; const SI32 count = ways->conteo;
			for(i = 0; i < count; i++){
				const STOsmDbWay* wayRef = ways->elemPtr(i);
				STOsmDbWay srch;
				srch.id = wayRef->id;
				const SI32 iFound = ways->indiceDe(srch);
				if(iFound == -1){
					PRINTF_ERROR("Way %lld is missing.\n", srch.id);
					NBASSERT(0)
				} else {
					PRINTF_INFO("Way %lld found!\n", srch.id);
					const STOsmDbWay* way = ways->elemPtr(iFound);
					STSceneMapWay newWay;
					STSceneMapWay_init(&newWay, this);
					newWay.id = way->id;
					//Build new way by nodes
					{
						SI32 i; const SI32 count = way->nodes->conteo;
						for(i = 0; i < count; i++){
							STOsmDbNode srchNode;
							srchNode.id = way->nodes->elem(i);
							const SI32 iFound = nodes->indiceDe(srchNode);
							if(iFound == -1){
								PRINTF_ERROR("Node %lld is missing.\n", srchNode.id);
								NBASSERT(0)
							} else {
								const STOsmDbNode* node = nodes->elemPtr(iFound);
								NBASSERT(node->lon != 0.0 && node->lat != 0.0)
								newWay.nodesPath->agregarCoordenadaLocal(node->lon * MAP_SCALE, node->lat * MAP_SCALE);
							}
						}
						//Remove if there's not enough nodes to build a lines-secuence
						const SI32 nodesCount = newWay.nodesPath->puntosLocales()->conteo;
						if(nodesCount < 2){
							PRINTF_WARNING("Just %d nodes.\n", newWay.nodesPath->puntosLocales()->conteo);
							STSceneMapWay_release(&newWay);
						} else {
							//PRINTF_INFO("OK %d nodes on route.\n", newWay.nodesPath->puntosLocales()->conteo);
							if(nodesCount < 3) newWay.nodesPath->establecerTipo(ENEscenaFiguraTipo_Linea);
							newWay.layer->agregarObjetoEscena(newWay.nodesPath);
							_layerMap->agregarObjetoEscena(newWay.layer);
							_waysVisual->agregarElemento(newWay);
						}
					}
				}
Ejemplo n.º 10
0
static struct usb_device_info * usb_device_is_valid(struct usb_device * dev) {

	int i;
	char product[1024];
	struct usb_device_info * ret = NULL;

	for ( i = 0; usb_devices[i].vendor; ++i ) {

		if ( dev->descriptor.idVendor == usb_devices[i].vendor && dev->descriptor.idProduct == usb_devices[i].product ) {

			printf("\b\b  ");
			PRINTF_END();
			PRINTF_ADD("Found ");
			usb_flash_device_info_print(&usb_devices[i]);
			PRINTF_END();

			PRINTF_LINE("Opening USB...");
			usb_dev_handle * udev = usb_open(dev);
			if ( ! udev ) {
				PRINTF_ERROR("usb_open failed");
				fprintf(stderr, "\n");
				return NULL;
			}

			usb_descriptor_info_print(udev, dev, product, sizeof(product));

#if defined(LIBUSB_HAS_GET_DRIVER_NP) && defined(LIBUSB_HAS_DETACH_KERNEL_DRIVER_NP)
			PRINTF_LINE("Detaching kernel from USB interface...");
			usb_detach_kernel_driver_np(udev, usb_devices[i].interface);
#endif

			PRINTF_LINE("Claiming USB interface...");
			if ( usb_claim_interface(udev, usb_devices[i].interface) < 0 ) {
				PRINTF_ERROR("usb_claim_interface failed");
				fprintf(stderr, "\n");
				usb_close(udev);
				return NULL;
			}

			if ( usb_devices[i].alternate >= 0 ) {
				PRINTF_LINE("Setting alternate USB interface...");
				if ( usb_set_altinterface(udev, usb_devices[i].alternate) < 0 ) {
					PRINTF_ERROR("usb_claim_interface failed");
					fprintf(stderr, "\n");
					usb_close(udev);
					return NULL;
				}
			}

			if ( usb_devices[i].configuration >= 0 ) {
				PRINTF_LINE("Setting USB configuration...");
				if ( usb_set_configuration(udev, usb_devices[i].configuration) < 0 ) {
					PRINTF_ERROR("usb_set_configuration failed");
					fprintf(stderr, "\n");
					usb_close(udev);
					return NULL;
				}
			}

			ret = calloc(1, sizeof(struct usb_device_info));
			if ( ! ret ) {
				ALLOC_ERROR();
				usb_close(udev);
				return NULL;
			}

			if ( strstr(product, "N900") )
				ret->device = DEVICE_RX_51;
			else
				ret->device = DEVICE_UNKNOWN;

			/* TODO: Autodetect more devices */

			if ( device_to_string(ret->device) )
				PRINTF_LINE("Detected USB device: %s", device_to_string(ret->device));
			else
				PRINTF_LINE("Detected USB device: (not detected)");
			PRINTF_END();

			if ( ret->device ) {
				enum device * device;
				for ( device = usb_devices[i].devices; *device; ++device )
					if ( *device == ret->device )
						break;
				if ( ! *device ) {
					ERROR("Device mishmash");
					fprintf(stderr, "\n");
					usb_close(udev);
					return NULL;
				}
			}

			ret->hwrev = -1;
			ret->flash_device = &usb_devices[i];
			ret->udev = udev;
			break;
		}
	}

	return ret;

}
Ejemplo n.º 11
0
NixUI8 loadDataFromWavFile(JNIEnv *env, jobject assetManager, const char* pathToWav, STNix_audioDesc* audioDesc, NixUI8** audioData, NixUI32* audioDataBytes){
	NixUI8 success = 0;
	AAssetManager* mgr = AAssetManager_fromJava(env, assetManager);
	AAsset* wavFile = AAssetManager_open(mgr, pathToWav, AASSET_MODE_UNKNOWN);
	//FILE* wavFile = fopen(pathToWav, "rb");
	if(wavFile==NULL){
		PRINTF_ERROR("WAV fopen failed: '%s'\n", pathToWav);
	} else {
		char chunckID[4]; AAsset_read(wavFile, chunckID, sizeof(char) * 4);
		if(chunckID[0]!='R' || chunckID[1]!='I' || chunckID[2]!='F' || chunckID[3]!='F'){
			PRINTF_ERROR("WAV chunckID not valid: '%s'\n", pathToWav);
		} else {
			NixUI8 continuarLectura	= 1;
			NixUI8 errorOpeningFile = 0;
			NixUI32 chunckSize; AAsset_read(wavFile, &chunckSize, sizeof(chunckSize) * 1);
			char waveID[4]; AAsset_read(wavFile, waveID, sizeof(char) * 4);
			if(waveID[0]!='W' || waveID[1]!='A' || waveID[2]!='V' || waveID[3]!='E'){
				PRINTF_ERROR("WAV::WAVE chunckID not valid: '%s'\n", pathToWav);
			} else {
				//Leer los subchuncks de WAVE
				char bufferPadding[64]; NixSI32 tamBufferPadding = 64; //Optimizacion para evitar el uso de fseek
				char subchunckID[4]; NixUI32 bytesReadedID = 0;
				NixUI8 formatChunckPresent = 0, chunckDataReaded = 0;
				do {
					bytesReadedID = (NixUI32)AAsset_read(wavFile, subchunckID, sizeof(char) * 4);
					if(bytesReadedID==4){
						NixUI32 subchunckBytesReaded = 0;
						NixUI32 subchunckSize; AAsset_read(wavFile, &subchunckSize, sizeof(subchunckSize) * 1);  //subchunckBytesReaded += sizeof(subchunckSize);
						NixUI8 tamanoChunckEsImpar = ((subchunckSize % 2)!=0);
						if(subchunckID[0]=='f' && subchunckID[1]=='m' && subchunckID[2]=='t' && subchunckID[3]==' '){
							if(!formatChunckPresent){
								//
								NixUI16 formato; AAsset_read(wavFile, &formato, sizeof(formato) * 1); subchunckBytesReaded += sizeof(formato);
								if(formato!=1 && formato!=3){ //WAVE_FORMAT_PCM=1 WAVE_FORMAT_IEEE_FLOAT=3
									errorOpeningFile = 1;
									PRINTF_ERROR("Wav format(%d) is not WAVE_FORMAT_PCM(1) or WAVE_FORMAT_IEEE_FLOAT(3)\n", formato);
								} else {
									NixUI16	canales;					AAsset_read(wavFile, &canales, sizeof(canales) * 1);									subchunckBytesReaded += sizeof(canales);
									NixUI32	muestrasPorSegundo;			AAsset_read(wavFile, &muestrasPorSegundo, sizeof(muestrasPorSegundo) * 1);				subchunckBytesReaded += sizeof(muestrasPorSegundo);
									NixUI32	bytesPromedioPorSegundo;	AAsset_read(wavFile, &bytesPromedioPorSegundo, sizeof(bytesPromedioPorSegundo) * 1);	subchunckBytesReaded += sizeof(bytesPromedioPorSegundo);
									NixUI16	alineacionBloques;			AAsset_read(wavFile, &alineacionBloques, sizeof(alineacionBloques) * 1);				subchunckBytesReaded += sizeof(alineacionBloques);
									NixUI16	bitsPorMuestra;				AAsset_read(wavFile, &bitsPorMuestra, sizeof(bitsPorMuestra) * 1);						subchunckBytesReaded += sizeof(bitsPorMuestra);
									//if((canales!=1 && canales!=2) || (bitsPorMuestra!=8 && bitsPorMuestra!=16 && bitsPorMuestra!=32) ||  (muestrasPorSegundo!=8000 && muestrasPorSegundo!=11025 && muestrasPorSegundo!=22050 && muestrasPorSegundo!=44100)){
									//	errorOpeningFile = 1;
									//	PRINTF_ERROR("Wav format not supported\n");
									//} else {
										//
										audioDesc->samplesFormat		= (formato==3 ? ENNix_sampleFormat_float : ENNix_sampleFormat_int);
										audioDesc->channels				= canales;
										audioDesc->bitsPerSample		= bitsPorMuestra;
										audioDesc->samplerate			= muestrasPorSegundo;
										audioDesc->blockAlign			= alineacionBloques;
									//}
									formatChunckPresent = 1;
								}
							}
						} else if(subchunckID[0]=='d' && subchunckID[1]=='a' && subchunckID[2]=='t' && subchunckID[3]=='a') {
							if(!formatChunckPresent){
								//WARNING
							} else if(chunckDataReaded){
								//WARNING
							} else {
								NixUI32 pcmDataBytes		= subchunckSize;
								*audioDataBytes			= pcmDataBytes; //printf("Tamano chunck PCM: %u\n", pcmDataBytes);
								if(*audioData!=NULL) free(*audioData);
								*audioData				= (NixUI8*)malloc(pcmDataBytes);
								NixUI32 bytesReaded		= (NixUI32)AAsset_read(wavFile, *audioData, sizeof(NixUI8) * pcmDataBytes);
								subchunckBytesReaded	+= bytesReaded;
								if(bytesReaded!=pcmDataBytes){
									//WARNING
								}
								chunckDataReaded = 1;
							}
						} else {
							if(chunckDataReaded){
								continuarLectura = 0;
							} else {
								AAsset_seek(wavFile, subchunckSize, SEEK_CUR);
								subchunckBytesReaded += subchunckSize;
							}
						}
						//Validar la cantidad de bytes leidos y el tamano del subchunck
						if(!errorOpeningFile && continuarLectura && subchunckBytesReaded!=subchunckSize){
							if(subchunckBytesReaded<subchunckSize){
								NixSI32 bytesPaddear = (subchunckSize-subchunckBytesReaded);
								if(bytesPaddear<=tamBufferPadding){
									AAsset_read(wavFile, bufferPadding, sizeof(char) * bytesPaddear); //Optimizacion para evitar el uso de fseek
								} else {
									AAsset_seek(wavFile, subchunckSize-subchunckBytesReaded, SEEK_CUR);
								}
							} else {
								errorOpeningFile = 1;
							}
						}
						//padding para tamano par de los subchuncks
						if(!errorOpeningFile && continuarLectura && tamanoChunckEsImpar) {
							char charPadding; AAsset_read(wavFile, &charPadding, sizeof(char) * 1);
						}
					}
				} while(bytesReadedID==4 && !errorOpeningFile && continuarLectura);
				success = (formatChunckPresent && chunckDataReaded && !errorOpeningFile) ? 1 : 0;
				if(!formatChunckPresent) PRINTF_WARNING("formatChunckPresent no leido\n");
				if(!chunckDataReaded) PRINTF_WARNING("chunckDataReaded no leido\n");
				if(errorOpeningFile) PRINTF_WARNING("errorOpeningFile error presente\n");
			}
		}
		AAsset_close(wavFile);
	}
	return success;
}
Ejemplo n.º 12
0
static int
printf_integer (STREAM *stream, struct printf_info *const pinfo, union printf_arg const *args)
{
  static const char digits_lower[] = "0123456789abcdefghijklmnopqrstuvwxyz";
  static const char digits_upper[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  const char *digits;

  unsigned base = SNV_POINTER_TO_UINT (pinfo->extra);
  uintmax_t value = 0L;
  int type, count_or_errorcode = SNV_OK;
  char buffer[256], *p, *end;
  boolean is_negative = FALSE;

  return_val_if_fail (pinfo != NULL, SNV_ERROR);

  /* Check for valid pre-state. */
  if (!(pinfo->state & (SNV_STATE_BEGIN | SNV_STATE_SPECIFIER)))
    {
      PRINTF_ERROR (pinfo, "out of range");
      return -1;
    }

  /* Upper or lower-case hex conversion? */
  digits = ((pinfo->spec >= 'a') && (pinfo->spec <= 'z'))
    ? digits_lower : digits_upper;

  if (pinfo->prec == -1)
    pinfo->prec = 0;

  /* Check for valid pre-state. */
  if (pinfo->prec < 0)
    {
      PRINTF_ERROR (pinfo, "invalid precision");
      return -1;
    }

  type = pinfo->type;

  /* Extract the correct argument from the arg vector. */
  if (type & PA_FLAG_UNSIGNED)
    {
      value = fetch_uintmax (pinfo, args);
      is_negative = FALSE;
      pinfo->showsign = pinfo->space = FALSE;
    }
  else
    {
      intmax_t svalue = 0L;
      svalue = fetch_intmax (pinfo, args);
      is_negative = (svalue < 0);
      value = (uintmax_t) ABS (svalue);
    }

  /* Convert the number into a string. */
  p = end = &buffer[sizeof (buffer) - 1];

  if (value == 0)
    *p-- = '0';

  else
    while (value > 0)
      {
	*p-- = digits[value % base];
	value /= base;
      }

  pinfo->width -= end - p;
  pinfo->prec -= end - p;

  /* Octal numbers have a leading zero in alterate form. */
  if (pinfo->alt && base == 8)
    {
      *p-- = '0';
      --pinfo->width;
    }

  /* Left pad with zeros to make up the precision. */
  if (pinfo->prec > 0)
    {
      pinfo->width -= pinfo->prec;
      while (pinfo->prec-- > 0)
	*p-- = '0';
    }

  /* Reserve room for leading `0x' for hexadecimal. */
  if (pinfo->alt && base == 16)
    pinfo->width -= 2;

  /* Reserve room for a sign character. */
  if (is_negative || pinfo->showsign || pinfo->space)
    --pinfo->width;

  /* Left pad to the remaining width if the supplied argument is less
   * than the width specifier, and the padding character is ' '.
   */
  if (pinfo->pad == ' ' && !pinfo->left)
    while ((count_or_errorcode >= 0) && (pinfo->width-- > 0))
      SNV_EMIT (pinfo->pad, stream, count_or_errorcode);

  /* Display any sign character. */
  if (count_or_errorcode >= 0)
    {
      if (is_negative)
	SNV_EMIT ('-', stream, count_or_errorcode);
      else if (pinfo->showsign)
	SNV_EMIT ('+', stream, count_or_errorcode);
      else if (pinfo->space)
	SNV_EMIT (' ', stream, count_or_errorcode);
    }

  /* Display `0x' for alternate hexadecimal specifier. */
  if ((count_or_errorcode >= 0) && (base == 16) && pinfo->alt)
    {
      SNV_EMIT ('0', stream, count_or_errorcode);
      SNV_EMIT (digits['X' - 'A' + 10], stream, count_or_errorcode);
    }

  /* Left pad to the remaining width if the supplied argument is less
   * than the width specifier, and the padding character is not ' '.
   */
  if (pinfo->pad != ' ' && !pinfo->left)
    while ((count_or_errorcode >= 0) && (pinfo->width-- > 0))
      SNV_EMIT (pinfo->pad, stream, count_or_errorcode);

  /* Fill the stream buffer with as many characters from the number
   * buffer as possible without overflowing.
   */
  while ((count_or_errorcode >= 0) && (++p < &buffer[sizeof (buffer)]))
    SNV_EMIT (*p, stream, count_or_errorcode);

  /* Right pad to the width if we still didn't reach the specified
   * width and the left justify flag was set.
   */
  if (pinfo->left)
    while ((count_or_errorcode >= 0) && (pinfo->width-- > 0))
      SNV_EMIT (pinfo->pad, stream, count_or_errorcode);

  /* Return the number of characters emitted. */
  return count_or_errorcode;
}
Ejemplo n.º 13
0
static int
printf_float (STREAM *stream,
	      struct printf_info *const pinfo,
	      union printf_arg const *args)
{
  snv_long_double value = 0.0;
  int sign, len, count_or_errorcode = SNV_OK;
#ifdef HAVE_LONG_DOUBLE
  char buffer[LDBL_MAX_10_EXP * 2 + 20], *p = buffer;
#else
  char buffer[DBL_MAX_10_EXP * 2 + 20], *p = buffer;
#endif

  return_val_if_fail (pinfo != NULL, SNV_ERROR);

  /* Check for valid pre-state */
  if (pinfo->prec == -1)
    pinfo->prec = SNV_POINTER_TO_INT (pinfo->extra);

  /* Check for valid pre-state. */
  if (pinfo->prec <= -1
     || pinfo->is_char || pinfo->is_short || pinfo->is_long)
    {
      PRINTF_ERROR (pinfo, "invalid flags");
      return -1;
    }

  /* Extract the correct argument from the arg vector. */
  value = fetch_double (pinfo, args);

  /* Convert the number into a string. */
  len = print_float (pinfo, buffer, buffer + sizeof (buffer), &sign, value);
  if (*buffer == '0')
    p++, len--;

  /* Compute the size of the padding.  */
  pinfo->width -= len;
  if (sign)
    pinfo->width--;

  /* Left pad to the remaining width if the supplied argument is less
     than the width specifier, and the padding character is ' '.  */
  if (pinfo->pad == ' ' && !pinfo->left)
    while ((count_or_errorcode >= 0) && (pinfo->width-- > 0))
      SNV_EMIT (pinfo->pad, stream, count_or_errorcode);

  /* Display any sign character. */
  if (count_or_errorcode >= 0 && sign)
    SNV_EMIT (sign, stream, count_or_errorcode);

  /* Left pad to the remaining width if the supplied argument is less
     than the width specifier, and the padding character is not ' '.  */
  if (pinfo->pad != ' ' && !pinfo->left)
    while ((count_or_errorcode >= 0) && (pinfo->width-- > 0))
	SNV_EMIT (pinfo->pad, stream, count_or_errorcode);

  /* Fill the stream buffer with as many characters from the number
     buffer as possible without overflowing.  */
  while ((count_or_errorcode >= 0) && (len-- > 0))
    SNV_EMIT (*p++, stream, count_or_errorcode);

  /* Right pad to the width if we still didn't reach the specified
     width and the left justify flag was set.  */
  if (pinfo->left)
    while ((count_or_errorcode >= 0) && (pinfo->width-- > 0))
      SNV_EMIT (pinfo->pad, stream, count_or_errorcode);

  /* Return the number of characters emitted. */
  return count_or_errorcode;
}
Ejemplo n.º 14
0
static int
printf_modifier_info (struct printf_info *const pinfo, size_t n, int *argtypes)
{
  return_val_if_fail (pinfo != NULL, SNV_ERROR);

  /* Check for valid pre-state. */
  if (!(pinfo->state & (SNV_STATE_BEGIN | SNV_STATE_MODIFIER)))
    {
      PRINTF_ERROR (pinfo, "out of range");
      return -1;
    }

  while (pinfo->state != SNV_STATE_SPECIFIER)
    {
      switch (*pinfo->format)
	{
	case 'h':
	  if (*++pinfo->format != 'h')
	    {
	      pinfo->is_short = TRUE;
	      break;
	    }

	  pinfo->is_char = TRUE;
	  pinfo->format++;
	  break;

	case 'z':
	  if (sizeof (size_t) > sizeof (char *))
	    pinfo->is_long_double = TRUE;
	  else
	    pinfo->is_long = TRUE;

	  pinfo->format++;
	  break;

	case 't':
	  if (sizeof (ptrdiff_t) > sizeof (char *))
	    pinfo->is_long_double = TRUE;
	  else
	    pinfo->is_long = TRUE;

	  pinfo->format++;
	  break;

	case 'l':
	  if (*++pinfo->format != 'l')
	    {
	      pinfo->is_long = TRUE;
	      break;
	    }
	 /*NOBREAK*/ 

	case 'j':
	case 'q':
	case 'L':
	  pinfo->is_long_double = TRUE;
	  pinfo->format++;
	  break;

	default:
	  pinfo->state = SNV_STATE_SPECIFIER;
	  pinfo->format--;
	  break;
	}
    }

  /* Return the number of characters emitted. */
  return 0;
}
Ejemplo n.º 15
0
/* This function has considerably more freedom than the others in
   playing with pinfo; in particular, it modifies argindex and can
   return completely bogus values whose only purpose is to extend
   the argtypes vector so that it has enough items for the positional
   parameter of the width (in the *n$ case).  It also expects that
   argtypes = (base of argtypes vector) + pinfo->argindex.

   This is messy, suggestion for simplifying it are gladly accepted.  */
static int
printf_numeric_param_info (struct printf_info *const pinfo, size_t n, int *argtypes)
{
  const char *pEnd = NULL;
  int found = 0, allowed_states, new_state;
  int position = 0, skipped_args = 0;
  long value;

  return_val_if_fail (pinfo != NULL, SNV_ERROR);

  /* If we are looking at a ``.'', then this is a precision parameter. */
  if (*pinfo->format == '.')
    {
      pinfo->format++;
      found |= 1;
    }

  /* First we might have a ``*''. */
  if (*pinfo->format == '*')
    {
      pinfo->format++;
      found |= 2;
    }

  /* Parse the number. */
  for (pEnd = pinfo->format, value = 0; *pEnd >= '0' && *pEnd <= '9'; pEnd++)
    value = value * 10 + (*pEnd - '0');

  if (pEnd > pinfo->format)
    {
      pinfo->format = pEnd;
      found |= 4;
    }

  if (value > INT_MAX)
    {
      PRINTF_ERROR (pinfo, "out of range");
      return -1;
    }

  /* And finally a dollar sign. */
  if (*pinfo->format == '$')
    {
      if (value == 0)
	{
          PRINTF_ERROR (pinfo, "invalid position specifier");
          return -1;
	}

      position = value;
      pinfo->format++;
      found |= 8;
    }

  switch (found & 14)
    {
    /* We found a * specification */
    case 2:
      if (pinfo->args)
	value = pinfo->args[pinfo->argindex].pa_int;
      if (n)
	argtypes[0] = PA_INT;
      pinfo->argindex++;
      skipped_args = 1;
      found ^= 6;
      break;

    /* We found a *n$ specification */
    case 14:
      if (n + pinfo->argindex > position - 1)
	argtypes[position - 1 - pinfo->argindex] = PA_INT;

      /* Else there is not enough space, reallocate and retry please...
         ... but we must say how much to skip.  */
      if (position >= pinfo->argindex)
        skipped_args = position - pinfo->argindex;

      if (pinfo->args)
	value = pinfo->args[position - 1].pa_int;
      found ^= 10;
      break;
    }

  switch (found)
    {
    /* We must have read a width specification. */
    case 4:
      allowed_states = SNV_STATE_BEGIN | SNV_STATE_WIDTH;
      new_state = ~(SNV_STATE_BEGIN | SNV_STATE_FLAG | SNV_STATE_WIDTH);

      /* How awful... */
      if (value < 0)
	{
	  pinfo->pad = ' ';
	  pinfo->left = TRUE;
	  value = -value;
	}

      pinfo->width = value;
      break;

    /* We must have read a precision specification. */
    case 5:
      allowed_states = SNV_STATE_PRECISION | SNV_STATE_BEGIN;
      new_state = SNV_STATE_MODIFIER | SNV_STATE_SPECIFIER;
      pinfo->prec = value;
      break;

    /* We must have read a position specification. */
    case 12:
      allowed_states = SNV_STATE_BEGIN;
      new_state = ~SNV_STATE_BEGIN;
      pinfo->dollar = position;
      break;

    /* We must have read something bogus. */
    default:
      PRINTF_ERROR (pinfo, "invalid specifier");
      return -1;
    }

  if (!(pinfo->state & allowed_states))
    {
      PRINTF_ERROR (pinfo, "invalid specifier");
      return -1;
    }

  pinfo->state = new_state;
  pinfo->format--;
  return skipped_args;
}