Ejemplo n.º 1
0
void test_tags()
{
  struct tag t;
  char test[2048];

  strcpy(test,"<tag type=tab col=30>");
  (void) read_tag(test, &t);
  print_tag(stdout, &t);
  printf("\ntype=%s\n", get_key_value(&t,"type"));
  strcpy(test,"<tag type=name name=\"Hebekiah the Jesuit\">");
  (void) read_tag(test, &t);
  print_tag(stdout, &t);
  printf("\nname=%s\n", get_key_value(&t,"name"));
};
Ejemplo n.º 2
0
Archivo: xml.c Proyecto: esneider/xml
static enum STATE read_xml ( FILE* file, struct xml_element* elem, bool root ) {

	enum STATE state;

	while ( true ) {

		skip_space( file );

		char c = fgetc( file );
		if ( c == EOF ) return root ? OK : PARSE_ERROR;
		ungetc( c, file );

		if ( c == '<' ) {

			struct xml_element* son = calloc( 1, sizeof( struct xml_element ) );
			if ( !son ) return MEMORY_ERROR;

			son->father = elem;
			son->next = elem->son;
			son->status = IS_ELEMENT_STATUS;

			state = read_tag( file, son );
			switch ( state ) {

				case OPEN_TAG:

					if ( son->next ) son->next->prev = son;
					elem->son = son;

					if ( ( state = read_xml ( file, son, false ) ) != OK )
						return state;
					break;

				case CLOSE_TAG:

					free( son );
					return OK;

				case ISOLATED_TAG:

					if ( son->next ) son->next->prev = son;
					elem->son = son;
					break;

				case OTHER_TAG:

					free( son );
					break;

				default:
					if ( son->next ) son->next->prev = son;
					elem->son = son;
					return state;
			}
		} else {
			state = read_value( file, elem );
			if ( state != OK ) return state;
		}
	}
}
Ejemplo n.º 3
0
/* comment interface */
tag_id get_free_tag(GapIO *io)
/*
 *
 */
{
    tag_id head;
    tagRecord freerec;
    tag_id free_id;

    (void) io_read_free_annotation(io,&head);
    if (head != 0) {
	/*
	 * if a free slot somewhere, use it
	 */
	free_id = head;
	(void) read_tag(io, free_id,&freerec);
	head = freerec.next;
	(void) io_write_free_annotation(io,&head);
    } else {
	/*
	 * extend file
	 */
	free_id = Nannotations(io)+1;
	io_init_annotations(io,free_id);
    }
    
    return free_id;
}
Ejemplo n.º 4
0
void
parse_patch1028_RRA_params(char **buf, rrd_t *rrd, int rra_index)
{
   int i;
   for (i = 0; i < MAX_RRA_PAR_EN; i++)
   {
   if (i == RRA_dependent_rra_idx ||
       i == RRA_seasonal_smooth_idx ||
       i == RRA_failure_threshold)
      read_tag(buf, "value","%lu",
         &(rrd->rra_def[rra_index].par[i].u_cnt));
   else
      read_tag(buf, "value","%lf",
         &(rrd->rra_def[rra_index].par[i].u_val));
   }
}
Ejemplo n.º 5
0
// get current config block from tag
BOOL get_config_block(BYTE *out, BYTE tagtype)
{
    int block;

    if(config_block_number(&block, tagtype))
        return read_tag(out, block, block);
    return FALSE;
}
Ejemplo n.º 6
0
 ///
 /// Constructor
 ///
 file_stream_device( std::string const& file_name
                   , read_tag   = read_tag()
                   )
 {
     io_error_if( _processor_ptr.get()->open_file( file_name.c_str() ) != LIBRAW_SUCCESS 
                , "file_stream_device: failed to open file"
                );
 }
Ejemplo n.º 7
0
 ///
 /// Constructor
 ///
 file_stream_device( const char* file_name
                   , read_tag   = read_tag()
                   )
 {
     io_error_if( _processor_ptr.get()->open_file( file_name ) != LIBRAW_SUCCESS 
                , "file_stream_device: failed to open file"
                );
 }
Ejemplo n.º 8
0
/* a backwards compatibility routine that will parse the CDP params section
 * generated by the aberrant patch to 1.0.28. */
void
parse_patch1028_CDP_params(char **buf, rrd_t *rrd, int rra_index, int ds_index)
{
   int ii;
   for (ii = 0; ii < MAX_CDP_PAR_EN; ii++)
   {
   if (cf_conv(rrd->rra_def[rra_index].cf_nam) == CF_FAILURES ||
       ii == CDP_unkn_pdp_cnt ||
       ii == CDP_null_count ||
       ii == CDP_last_null_count)
   {
      read_tag(buf,"value","%lu",
       &(rrd->cdp_prep[rrd->stat_head->ds_cnt*(rra_index) + ds_index].scratch[ii].u_cnt));
   } else {
      read_tag(buf,"value","%lf",&(rrd->cdp_prep[rrd->stat_head->ds_cnt*
       (rra_index) + ds_index].scratch[ii].u_val));
   }
   }
}
Ejemplo n.º 9
0
void init()		//read all the needed input files
{
	read_place_name();
	read_place_belong();
	read_tag();
	read_Person_location();
	read_study_org();
	read_work_org();
	read_org_location();
	read_graph();
}
Ejemplo n.º 10
0
static void read_text(FILE *txt)
  {
  int i;
  int xs;
  char ss[2] =" ";
  char wsp = 1;

  buff_pos = 0;
  buff_end = 0;
  xs = 0;
  do
     {
     i = fgetc(txt);
     if (i == EOF) break;
     if (i<32) i = 32;
     if (i =='<')
        {
        if (read_tag(txt))
           {
           xs = 0;
           wsp = 1;
           }
        continue;
        }
     if (i =='[')
        {
        if (skip_section(txt)) break;
        continue;
        }
     if (i == 32)
        {
        if (wsp) continue;
        buff_pos = buff_end;
        wsp = 1;
        }
     else wsp = 0;
     if (i =='&') i = fgetc(txt);
     if (winconv && i>137) i = xlat_table[i-138];
     ss[0] = i;
     xs += text_width(ss);
     read_buff[buff_end++] = i;
     if (xs>total_width && !wsp)
        {
        save_buffer();
        read_buff[buff_end] = 0;
        xs = text_width(read_buff);
        }
     }
  while (1);
  }
Ejemplo n.º 11
0
void
parse_FAILURES_history(char **buf, rrd_t *rrd, int rra_index, int ds_index)
{
   char history[MAX_FAILURES_WINDOW_LEN + 1];
   char *violations_array;
   unsigned short i;

   /* 28 = MAX_FAILURES_WINDOW_LEN */ 
   read_tag(buf, "history", "%28[0-1]", history);
   violations_array = (char*) rrd -> cdp_prep[rrd->stat_head->ds_cnt*(rra_index)
      + ds_index].scratch;
   
   for (i = 0; i < rrd -> rra_def[rra_index].par[RRA_window_len].u_cnt; ++i)
      violations_array[i] = (history[i] == '1') ? 1 : 0;

}
Ejemplo n.º 12
0
static int read_header(AVFormatContext *s)
{
    AVDictionary **m = &s->metadata;
    uint8_t line[1024];

    while(!avio_feof(s->pb)) {
        get_line(s->pb, line, sizeof(line));

        if (!memcmp(line, ID_STREAM, strlen(ID_STREAM))) {
            AVStream *st = avformat_new_stream(s, NULL);

            if (!st)
                return AVERROR(ENOMEM);

            st->codec->codec_type = AVMEDIA_TYPE_DATA;
            st->codec->codec_id   = AV_CODEC_ID_FFMETADATA;

            m = &st->metadata;
        } else if (!memcmp(line, ID_CHAPTER, strlen(ID_CHAPTER))) {
            AVChapter *ch = read_chapter(s);

            if (!ch)
                return AVERROR(ENOMEM);

            m = &ch->metadata;
        } else
            read_tag(line, m);
    }

    s->start_time = 0;
    if (s->nb_chapters) {
#ifdef IDE_COMPILE
        AVRational tmp;

        tmp.num = 1;
		tmp.den = AV_TIME_BASE;
		s->duration = av_rescale_q(s->chapters[s->nb_chapters - 1]->end,
                                   s->chapters[s->nb_chapters - 1]->time_base,
                                   tmp);
#else
		s->duration = av_rescale_q(s->chapters[s->nb_chapters - 1]->end,
                                   s->chapters[s->nb_chapters - 1]->time_base,
                                   AV_TIME_BASE_Q);
#endif
	}
    return 0;
}
Ejemplo n.º 13
0
void blank_tag_rec(GapIO *io, tag_id t)
/*
 * Blank out fields in tag record t
 */
{
    tagRecord r;
    
    (void) read_tag(io, t, &r);
    
    r.position = 0;
    r.length = 0;
    r.type.i = 0x20202020;
    r.comment = 0;
    r.next = 0;
    r.sense = 0;
    
    (void) write_tag(io, t,r);
}
Ejemplo n.º 14
0
static int read_header(AVFormatContext *s, AVFormatParameters *ap)
{
    AVMetadata **m = &s->metadata;
    uint8_t line[1024];

    while(!url_feof(s->pb)) {
        get_line(s->pb, line, sizeof(line));

        if (!memcmp(line, ID_STREAM, strlen(ID_STREAM))) {
            AVStream *st = av_new_stream(s, 0);

            if (!st)
                return -1;

            st->codec->codec_type = AVMEDIA_TYPE_DATA;
            st->codec->codec_id   = CODEC_ID_FFMETADATA;

            m = &st->metadata;
        } else if (!memcmp(line, ID_CHAPTER, strlen(ID_CHAPTER))) {
            AVChapter *ch = read_chapter(s);

            if (!ch)
                return -1;

            m = &ch->metadata;
        } else
            read_tag(line, m);
    }

    s->start_time = 0;
    if (s->nb_chapters)
        s->duration = av_rescale_q(s->chapters[s->nb_chapters - 1]->end,
                                   s->chapters[s->nb_chapters - 1]->time_base,
                                   AV_TIME_BASE_Q);

    return 0;
}
Ejemplo n.º 15
0
void delete_tag_rec(GapIO *io, tag_id t)
/*
 * remove t from file, discarding comment if necessary
 */
{
    tag_id head;
    tagRecord freerec;

    /*
     * reclaim comment
     */
    freerec.comment = 0; /* just in case read_tag fails */
    (void) read_tag(io, t,&freerec);
    if (freerec.comment) {
	deallocate(io, freerec.comment);
	freerec.comment = 0;
    }
    
    (void) io_read_free_annotation(io,&head);
    freerec.next = head;
    (void) write_tag(io, t,freerec);
    head = t;
    (void) io_write_free_annotation(io,&head);
}
   // ----------------------------------------------------------------------
   shawn::Vec
   PropertyTagColorVecTask::PropertyTagColorVec::
   value( double,
          const PropertyStack<shawn::Vec>&,
          const Element& e) 
      const throw()
   { 
      shawn::Vec out;

      //Looking for the provided (double) tag:
      double tagval = read_tag(e);
      
      if(tagval < 0.0)
      {
         // Tag not available or not compatible, so the node gets a gray color:
         out = shawn::Vec(0.5, 0.5, 0.5);
      }
      else
      {
         // Tag available, red for a tag-value of 0.0 and blue for a value of 1.0:
         out = shawn::Vec(1.0-tagval, 0.0, tagval);
      }
      return out;
   }
Ejemplo n.º 17
0
void insert_new_tag2(GapIO *io, int into,
		     int *cache, int cache_len, int *cache_pos,
		     int pos, int length, char *type, char *comment, int sense)
{
    tag_id prev, next, newt;
    tagRecord prev_tag, next_tag, new_tag;
    int i;

    /* Initialise cache if required */
    if (pos >= *cache_pos) {
	next = cache[*cache_pos];
	if (!next)
	    next = first_tag(io, into);
	while (next) {
	    read_tag(io, next, &next_tag);
	    if (next_tag.position < *cache_pos) {
		next = next_tag.next;
		continue;
	    }
	    if (next_tag.position > pos)
		break;
	    for (i = *cache_pos; i < next_tag.position; i++)
		cache[i] = cache[*cache_pos];
	    for (; i <= next_tag.position; i++) {
		cache[i] = next;
	    }
	    *cache_pos = i-1;
	    next = next_tag.next;
	}
	for (i = *cache_pos+1; i <= pos; i++)
	    cache[i] = cache[*cache_pos];
	*cache_pos = pos;
    }

    /* Find previous and next tags - quick lookup in cache */
    prev = cache[pos];
    if (!prev) {
	next = first_tag(io, into);
    } else {
	read_tag(io, prev, &prev_tag);
	next = prev_tag.next;
    }

    /* Create and initialise new tag */
    newt = get_free_tag(io);
    new_tag.position = pos;
    new_tag.length = length;
    strncpy(new_tag.type.c,type,4);
    if (comment!=NULL)
	new_tag.comment = put_comment(io, comment);
    else
	new_tag.comment = 0;
    new_tag.next = next;
    new_tag.sense = sense;
    write_tag(io, newt, new_tag);

    /* Update cache */
    i = pos;
    while (i <= *cache_pos && cache[i] == prev)
	cache[i++] = newt;
    if (pos > *cache_pos) {
	int j, k = cache[*cache_pos];
	for (j = *cache_pos; j < pos; j++)
	    cache[j] = k;
	cache[pos] = newt;
	*cache_pos = pos;
    }
    
    /* Link previous tag */
    if (prev) {
	prev_tag.next = newt;
	write_tag(io, prev, prev_tag);
    } else {
	update_tag(io, into, newt);
    }
}
Ejemplo n.º 18
0
/*
 * ---------------------------------------------------------------------------
 *  parse_xbv1
 *
 *      Scan the firmware file to find the TLVs we are interested in.
 *      Actions performed:
 *        - check we support the file format version in VERF
 *      Store these TLVs if we have a firmware image:
 *        - SLTP Symbol Lookup Table Pointer
 *        - FWDL firmware download segments
 *        - FWOL firmware overlay segment
 *        - VMEQ Register probe tests to verify matching h/w
 *      Store these TLVs if we have a patch file:
 *        - FWID the firmware build ID that this file patches
 *        - PTDL The actual patches
 *
 *      The structure pointed to by fwinfo is cleared and
 *      'fwinfo->mode' is set to 'unknown'.  The 'fwinfo->mode'
 *      variable is set to 'firmware' or 'patch' once we know which
 *      sort of XBV file we have.
 *
 *  Arguments:
 *      readfn          Pointer to function to call to read from the file.
 *      dlpriv          Opaque pointer arg to pass to readfn.
 *      fwinfo          Pointer to fwinfo struct to fill in.
 *
 *  Returns:
 *      CSR_RESULT_SUCCESS on success, CSR error code on failure
 * ---------------------------------------------------------------------------
 */
CsrResult xbv1_parse(card_t *card, fwreadfn_t readfn, void *dlpriv, xbv1_t *fwinfo)
{
    ct_t ct;
    tag_t tag;
    xbv_stack_t stack;

    ct.dlpriv = dlpriv;
    ct.ioffset = 0;
    ct.iread = readfn;

    CsrMemSet(fwinfo, 0, sizeof(xbv1_t));
    fwinfo->mode = xbv_unknown;

    /* File must start with XBV1 triplet */
    if (read_tag(card, &ct, &tag) <= 0)
    {
        unifi_error(NULL, "File is not UniFi firmware\n");
        return CSR_WIFI_HIP_RESULT_INVALID_VALUE;
    }

    DBG_TAG(tag.t_name);

    if (!TAG_EQ(tag.t_name, "XBV1"))
    {
        unifi_error(NULL, "File is not UniFi firmware (%s)\n", tag.t_name);
        return CSR_WIFI_HIP_RESULT_INVALID_VALUE;
    }

    stack.ptr = 0;
    stack.s[stack.ptr].container = xbv_xbv1;
    stack.s[stack.ptr].ioffset_end = XBV_MAX_OFFS;

    /* Now scan the file */
    while (1)
    {
        CsrInt32 n;

        n = read_tag(card, &ct, &tag);
        if (n < 0)
        {
            unifi_error(NULL, "No tag\n");
            return CSR_WIFI_HIP_RESULT_INVALID_VALUE;
        }
        if (n == 0)
        {
            /* End of file */
            break;
        }

        DBG_TAG(tag.t_name);

        /* File format version */
        if (TAG_EQ(tag.t_name, "VERF"))
        {
            CsrUint32 version;

            if (xbv_check(fwinfo, &stack, xbv_unknown, xbv_xbv1) ||
                (tag.t_len != 2) ||
                read_uint(card, &ct, &version, 2))
            {
                return CSR_WIFI_HIP_RESULT_INVALID_VALUE;
            }
            if (version != 0)
            {
                unifi_error(NULL, "Unsupported firmware file version: %d.%d\n",
                            version >> 8, version & 0xFF);
                return CSR_WIFI_HIP_RESULT_INVALID_VALUE;
            }
        }
Ejemplo n.º 19
0
// Handler for EXIF data
static
    cmsBool HandleEXIF(struct jpeg_decompress_struct* cinfo)
{
    jpeg_saved_marker_ptr ptr;
    uint32_t ifd_ofs;
    int pos = 0, swapBytes = 0;
    uint32_t i, numEntries;
    double XRes = -1, YRes = -1;
    int Unit = 2; // Inches


    for (ptr = cinfo ->marker_list; ptr; ptr = ptr ->next) {

        if ((ptr ->marker == JPEG_APP0+1) && ptr ->data_length > 6) {
            JOCTET FAR* data = ptr -> data;

            if (memcmp(data, "Exif\0\0", 6) == 0) {

                data += 6; // Skip EXIF marker

                // 8 byte TIFF header
                // first two determine byte order
                pos = 0;
                if (read16(data, pos, 0) == INTEL_BYTE_ORDER) {
                    swapBytes = 1;
                }

                pos += 2;

                // next two bytes are always 0x002A (TIFF version)
                pos += 2;

                // offset to Image File Directory (includes the previous 8 bytes)
                ifd_ofs = read32(data, pos, swapBytes);

                // Search the directory for resolution tags
                numEntries = read16(data, ifd_ofs, swapBytes);

                for (i=0; i < numEntries; i++) {

                    uint32_t entryOffset = ifd_ofs + 2 + (12 * i);
                    uint32_t tag = read16(data, entryOffset, swapBytes);

                    switch (tag) {

                    case RESOLUTION_UNIT:
                        if (!read_tag(data, entryOffset, swapBytes, &Unit)) return FALSE;
                        break;

                    case XRESOLUTION:
                        if (!read_tag(data, entryOffset, swapBytes, &XRes)) return FALSE;
                        break;

                    case YRESOLUTION:
                        if (!read_tag(data, entryOffset, swapBytes, &YRes)) return FALSE;
                        break;

                    default:;
                    }

                }

                // Proceed if all found

                if (XRes != -1 && YRes != -1)
                {

                    // 1 = None
                    // 2 = inches
                    // 3 = cm

                    switch (Unit) {

                    case 2:

                        cinfo ->X_density = (UINT16) floor(XRes + 0.5);
                        cinfo ->Y_density = (UINT16) floor(YRes + 0.5);
                        break;

                    case 1:

                        cinfo ->X_density = (UINT16) floor(XRes * 2.54 + 0.5);
                        cinfo ->Y_density = (UINT16) floor(YRes * 2.54 + 0.5);
                        break;

                    default: return FALSE;
                    }

                    cinfo ->density_unit = 1;  /* 1 for dots/inch, or 2 for dots/cm.*/

                }


            }
        }
    }
    return FALSE;
}
Ejemplo n.º 20
0
void* wav_read_open(const char *filename) {
	struct wav_reader* wr = (struct wav_reader*) malloc(sizeof(*wr));
	long data_pos = 0;
	memset(wr, 0, sizeof(*wr));

	wr->wav = fopen(filename, "rb");
	if (wr->wav == NULL) {
		free(wr);
		return NULL;
	}

	while (1) {
		uint32_t tag, tag2, length;
		tag = read_tag(wr);
		if (feof(wr->wav))
			break;
		length = read_int32(wr);
		if (tag != TAG('R', 'I', 'F', 'F') || length < 4) {
			fseek(wr->wav, length, SEEK_CUR);
			continue;
		}
		tag2 = read_tag(wr);
		length -= 4;
		if (tag2 != TAG('W', 'A', 'V', 'E')) {
			fseek(wr->wav, length, SEEK_CUR);
			continue;
		}
		// RIFF chunk found, iterate through it
		while (length >= 8) {
			uint32_t subtag, sublength;
			subtag = read_tag(wr);
			if (feof(wr->wav))
				break;
			sublength = read_int32(wr);
			length -= 8;
			if (length < sublength)
				break;
			if (subtag == TAG('f', 'm', 't', ' ')) {
				if (sublength < 16) {
					// Insufficient data for 'fmt '
					break;
				}
				wr->format          = read_int16(wr);
				wr->channels        = read_int16(wr);
				wr->sample_rate     = read_int32(wr);
				wr->byte_rate       = read_int32(wr);
				wr->block_align     = read_int16(wr);
				wr->bits_per_sample = read_int16(wr);
				fseek(wr->wav, sublength - 16, SEEK_CUR);
			} else if (subtag == TAG('d', 'a', 't', 'a')) {
				data_pos = ftell(wr->wav);
				wr->data_length = sublength;
				fseek(wr->wav, sublength, SEEK_CUR);
			} else {
				fseek(wr->wav, sublength, SEEK_CUR);
			}
			length -= sublength;
		}
		if (length > 0) {
			// Bad chunk?
			fseek(wr->wav, length, SEEK_CUR);
		}
	}
	fseek(wr->wav, data_pos, SEEK_SET);
	return wr;
}
Ejemplo n.º 21
0
Archivo: server.c Proyecto: lxdcn/fss
void server_polling(int listener)
{
  int i, fd, res_num;
  ssize_t n;
  uint64_t tag;
  nfds_t pfd_num = MAX_CLIENTS + 1; // + 1 for listener itself
  struct pollfd pfd[pfd_num];
  client = pfd;
  struct sockaddr cliaddr;
  socklen_t cliaddrlen;
  
  for (i = 0; i < pfd_num; i++)
    pfd[i].fd = -1;

  pfd[0].fd = listener;
  pfd[0].events = POLLIN;

  while (1) {
    Log(LOG_DEBUG, "polling.......");
    if ((res_num = poll(pfd, pfd_num, 10000)) < 0)
      Log_die(DIE_FAILURE, LOG_ERR, "poll() failed");

    if (pfd[0].revents & POLLIN) { // acceptable
      cliaddrlen = sizeof(struct sockaddr);
      if ((fd = accept(listener, &cliaddr, &cliaddrlen)) < 0)
	Log_die(DIE_FAILURE, LOG_ERR, "accept() failed");

      for (i = 1; i < pfd_num; i++)
	if (pfd[i].fd < 0) {
	  pfd[i].fd = fd;
	  //set_nonblock(pfd[i].fd);
	  break;
	}
      
      if (i == pfd_num)
	Log(LOG_WARNING, "client number over upper limit %d", MAX_CLIENTS);
      else {
	pfd[i].events = POLLIN;
	Log(LOG_NOTICE, "client[%d] connected", i);
      }

      if (--res_num <= 0)
	continue;
    }

    for (i = 1; i < pfd_num; i++) {
      if ((fd = pfd[i].fd) < 0)
	continue;

      if (pfd[i].revents & (POLLIN | POLLERR)) {
	tag = read_tag(fd, NULL);
	//read_tag(fd, &tag, sizeof(tag), NULL);
	if ((n < 0 && errno == ECONNRESET) || n == 0) {
	  Log(LOG_NOTICE, "client[%d] reseted/closed connection", i);
	  kill_client(pfd, i);
	} else if (n < 0)
	  Log_die(DIE_FAILURE, LOG_ERR, "read from client[i] failed", i);
	else {
	  client_idx = i;
	  tag_switch(tag, fd);
	}
      }

      if (--res_num <= 0)
	break;
    }
    
  } // end for while(1) ..
  
}
Ejemplo n.º 22
0
static readstat_error_t read_por_file_data(readstat_por_ctx_t *ctx) {
    int i;
    char string[256];
    char error_buf[1024];
    int retval = 0;
    readstat_error_t rs_retval = READSTAT_OK;

    while (1) {
        for (i=0; i<ctx->var_count; i++) {
            spss_varinfo_t *info = &ctx->varinfo[i];
            readstat_value_t value = { .type = info->type };

            if (info->type == READSTAT_TYPE_STRING) {
                retval = read_string(ctx, string, sizeof(string));
                if (i == 0 && retval == 1) {
                    return 0;
                } else if (retval == -1) {
                    if (ctx->error_handler) {
                        snprintf(error_buf, sizeof(error_buf), "Error in %s\n", info->name);
                        ctx->error_handler(error_buf, ctx->user_ctx);
                    }
                    rs_retval = READSTAT_ERROR_PARSE;
                    goto cleanup;
                }
                value.v.string_value = string;
//                printf("String value: %s\n", string);
            } else if (info->type == READSTAT_TYPE_DOUBLE) {
                retval = read_double(ctx, &value.v.double_value);
                if (i == 0 && retval == 1) {
                    return READSTAT_OK;
                } else if (retval != 0) {
                    if (ctx->error_handler) {
                        snprintf(error_buf, sizeof(error_buf), "Error in %s\n", info->name);
                        ctx->error_handler(error_buf, ctx->user_ctx);
                    }
                    rs_retval = READSTAT_ERROR_PARSE;
                    goto cleanup;
                }
                spss_tag_missing_double(&value, &info->missingness);
            }
            ctx->value_handler(ctx->obs_count, i, value, ctx->user_ctx);
        }
        ctx->obs_count++;

        rs_retval = por_update_progress(ctx);
        if (rs_retval != READSTAT_OK)
            break;
    }
cleanup:
    return rs_retval;
}

readstat_error_t readstat_parse_por(readstat_parser_t *parser, const char *filename, void *user_ctx) {
    readstat_error_t retval = READSTAT_OK;
    unsigned char reverse_lookup[256];
    char vanity[200];

    readstat_por_ctx_t *ctx = calloc(1, sizeof(readstat_por_ctx_t));

    ctx->space = ' ';
    ctx->var_dict = ck_hash_table_init(1024);
    ctx->info_handler = parser->info_handler;
    ctx->variable_handler = parser->variable_handler;
    ctx->value_handler = parser->value_handler;
    ctx->value_label_handler = parser->value_label_handler;
    ctx->error_handler = parser->error_handler;
    ctx->progress_handler = parser->progress_handler;
    ctx->user_ctx = user_ctx;

    if ((ctx->fd = readstat_open(filename)) == -1) {
        free(ctx);
        return READSTAT_ERROR_OPEN;
    }

    if ((ctx->file_size = lseek(ctx->fd, 0, SEEK_END)) == -1) {
        retval = READSTAT_ERROR_READ;
        goto cleanup;
    }

    if (lseek(ctx->fd, 0, SEEK_SET) == -1) {
        retval = READSTAT_ERROR_READ;
        goto cleanup;
    }

    if (read_bytes(ctx, vanity, sizeof(vanity)) != sizeof(vanity)) {
        retval = READSTAT_ERROR_READ;
        goto cleanup;
    }

    if (read_bytes(ctx, reverse_lookup, sizeof(reverse_lookup)) != sizeof(reverse_lookup)) {
        retval = READSTAT_ERROR_READ;
        goto cleanup;
    }

    ctx->space = reverse_lookup[126];

    int i;

    for (i=0; i<256; i++)
        ctx->lookup[reverse_lookup[i]] = unicode_lookup[i];

    unsigned char check[9];
    char tr_check[9];

    if (read_bytes(ctx, check, sizeof(check)-1) != sizeof(check)-1) {
        retval = READSTAT_ERROR_READ;
        goto cleanup;
    }

    check[8] = '\0';

    utf8_encode(check, sizeof(check), tr_check, sizeof(tr_check), ctx->lookup);

    if (strcmp("SPSSPORT", tr_check) != 0) {
        retval = READSTAT_ERROR_PARSE;
        goto cleanup;
    }

    ctx->var_offset = -1;

    unsigned char version;
    char string[256];

    if (read_bytes(ctx, &version, sizeof(version)) != sizeof(version)) {
        retval = READSTAT_ERROR_READ;
        goto cleanup;
    }
    if (read_string(ctx, string, sizeof(string)) == -1) { /* creation date */
        retval = READSTAT_ERROR_PARSE;
        goto cleanup;
    }
    if (read_string(ctx, string, sizeof(string)) == -1) { /* creation time */
        retval = READSTAT_ERROR_PARSE;
        goto cleanup;
    }

    while (1) {
        uint16_t tr_tag = read_tag(ctx);
        switch (tr_tag) {
        case '1': /* product ID */
        case '2': /* author ID */
        case '3': /* sub-product ID */
            if (read_string(ctx, string, sizeof(string)) == -1) {
                retval = READSTAT_ERROR_PARSE;
                goto cleanup;
            }
            break;
        case '4': /* variable count */
            retval = read_variable_count_record(ctx);
            if (retval != READSTAT_OK)
                goto cleanup;
            break;
        case '6': /* case weight */
            retval = read_case_weight_record(ctx);
            if (retval != READSTAT_OK)
                goto cleanup;
            break;
        case '7': /* variable */
            retval = read_variable_record(ctx);
            if (retval != READSTAT_OK)
                goto cleanup;
            break;
        case '8': /* missing value */
            retval = read_missing_value_record(ctx);
            if (retval != READSTAT_OK)
                goto cleanup;
            break;
        case 'B': /* missing value range */
            retval = read_missing_value_range_record(ctx);
            if (retval != READSTAT_OK)
                goto cleanup;
            break;
        case '9': /* LO THRU x */
            retval = read_missing_value_lo_range_record(ctx);
            if (retval != READSTAT_OK)
                goto cleanup;
            break;
        case 'A': /* x THRU HI */
            retval = read_missing_value_hi_range_record(ctx);
            if (retval != READSTAT_OK)
                goto cleanup;
            break;
        case 'C': /* variable label */
            retval = read_variable_label_record(ctx);
            if (retval != READSTAT_OK)
                goto cleanup;
            break;
        case 'D': /* value label */
            retval = read_value_label_record(ctx);
            if (retval != READSTAT_OK)
                goto cleanup;
            break;
        case 'E': /* document record */
            retval = read_document_record(ctx);
            if (retval != READSTAT_OK)
                goto cleanup;
            break;
        case 'F': /* file data */
            if (ctx->var_offset != ctx->var_count - 1) {
                retval = READSTAT_ERROR_PARSE;
                goto cleanup;
            }
            for (i=0; i<ctx->var_count; i++) {
                char label_name_buf[256];
                spss_varinfo_t *info = &ctx->varinfo[i];
                info->missingness = spss_missingness_for_info(info);

                readstat_variable_t *variable = spss_init_variable_for_info(info);

                snprintf(label_name_buf, sizeof(label_name_buf), POR_LABEL_NAME_PREFIX "%d", info->labels_index);

                int cb_retval = ctx->variable_handler(i, variable,
                                                      info->labels_index == -1 ? NULL : label_name_buf,
                                                      user_ctx);

                spss_free_variable(variable);

                if (cb_retval) {
                    retval = READSTAT_ERROR_USER_ABORT;
                    goto cleanup;
                }
            }
            if (parser->fweight_handler && ctx->fweight_name[0]) {
                for (i=0; i<ctx->var_count; i++) {
                    spss_varinfo_t *info = &ctx->varinfo[i];
                    if (strcmp(info->name, ctx->fweight_name) == 0) {
                        if (parser->fweight_handler(i, user_ctx)) {
                            retval = READSTAT_ERROR_USER_ABORT;
                            goto cleanup;
                        }
                        break;
                    }
                }
            }
            retval = read_por_file_data(ctx);
            if (retval != READSTAT_OK)
                goto cleanup;

            if (parser->info_handler) {
                if (parser->info_handler(ctx->obs_count, ctx->var_count, ctx->user_ctx)) {
                    retval = READSTAT_ERROR_USER_ABORT;
                }
            }
            goto cleanup;

            break;
        default:
            retval = READSTAT_ERROR_PARSE;
            goto cleanup;

            break;
        }
    }

cleanup:
    readstat_close(ctx->fd);
    por_ctx_free(ctx);

    return retval;
}
Ejemplo n.º 23
0
int main(int argc, char **argv)
{
_comm_header *comm;
_tag_detail *tag;
_path *path;
_rack *rack;
_services *services;
//_backplane_data *backplane;
int result,x,debug=0;

result = 0;

  while ((x = getopt(argc, argv, "dh?")) != -1)
  {
    switch (x)
    {
    case 'd':
      debug++;
      break;
    case 'h':
    case '?':
      helpme();
      exit(1);
    }
  }


	
// Note that this is quick and dirty - no error checking...

tag = malloc(sizeof(_tag_detail));
memset(tag,0,sizeof(_tag_detail));

rack = malloc(sizeof(_rack));
memset (rack,0,sizeof(_rack));

//backplane = malloc(sizeof(_backplane_data));
//memset (backplane,0,sizeof(_backplane_data));

path = malloc(sizeof(_path));
memset (path,0,sizeof(_path));

services = malloc(sizeof(_services));
memset (services,0,sizeof(_services));

comm = malloc(sizeof(_comm_header));
memset (comm,0,sizeof(_comm_header));

dprint (DEBUG_TRACE,"setting plc name %d %s.\n",strlen(argv[1]), argv[1]);
comm->hostname = argv[1];
dprint (DEBUG_TRACE,"attaching to plc\n");

establish_connection (comm, services, 0);
if (comm->error != 0)
	{
	printf ("Could not attach to %s\n",argv[1]);
	exit(-1);
	}
path->device1 = -1;
path->device2 = -1;
path->device3 = -1;
path->device4 = -1;
path->device5 = -1;
path->device6 = -1;
path->device7 = -1;
path->device8 = -1;

//get_backplane_data(comm, backplane, rack, path, 0);
dprint (DEBUG_TRACE,"polling PLC rack layout\n");
who(comm, rack, NULL, 0);
path->device1 =1;
path->device2 = rack->cpulocation;
dprint (DEBUG_TRACE,"reading tag\n");
if (argc == 3)
	result = read_tag(comm, path, NULL, argv[2], tag, 0);
if (argc == 4)
	result = read_tag(comm, path, argv[3], argv[2], tag, 0);

if (result != 0)
	{
	printf ("reading tag %s failed - does it exist?\n\n",argv[2]);
	exit(-1);
	}
for (x=0; x<tag->datalen; x++)
	printf ("%02X ",tag->data[x]);
printf ("\n\n");
exit(0);
}
   // ----------------------------------------------------------------------
   shawn::Vec
   PropertyIndexedTagColorVecTask::PropertyIndexedTagColorVec::
   value( double,
          const PropertyStack<shawn::Vec>&,
          const Element& e) 
      const throw()
   { 
      shawn::Vec out;

      //Looking for the provided (double) tag:
      int tagval = read_tag(e);
      
      switch(tagval)
	  {
		  case 0:
			  out = shawn::Vec(0,0,0);
			  break;
		  case 1:
			  out = shawn::Vec(0.5,0.5,0.5);
			  break;
		  case 2:
			  out = shawn::Vec(0.5,0,0);
			  break;
		  case 3:
			  out = shawn::Vec(0.5,0.5,0.0);
			  break;
		  case 4:
			  out = shawn::Vec(1.0,1.0,1.0);
			  break;
		  case 5:
			  out = shawn::Vec(0.75,0.75,0.75);
			  break;
		  case 6:
			  out = shawn::Vec(1.0,0.0,0.0);
			  break;
		  case 7:
			  out = shawn::Vec(1.0,1.0,0.0);
			  break;
		  case 8:
			  out = shawn::Vec(0.0,0.5,0.0);
			  break;
		  case 9:
			  out = shawn::Vec(0.0,0.5,0.5);
			  break;
		  case 10:
			  out = shawn::Vec(0.0,0.0,0.5);
			  break;
		  case 11:
			  out = shawn::Vec(0.5,0.0,0.5);
			  break;
		  case 12:
			  out = shawn::Vec(0.0,1.0,0.0);
			  break;
		  case 13:
			  out = shawn::Vec(0.0,1.0,1.0);
			  break;
		  case 14:
			  out = shawn::Vec(0.0,0.0,1.0);
			  break;
		  case 15:
			  out = shawn::Vec(1.0,0.0,1.0);
			  break;
		  default:
			  out = shawn::Vec(0.33,0.33,0.33);
			  break;
	  }
	  
      return out;
   }
Ejemplo n.º 25
0
/* parse the data stored in buf and return a filled rrd structure */
int xml2rrd(char* buf, rrd_t* rrd, char rc){
  /* pass 1 identify number of RRAs  */
  char *ptr,*ptr2,*ptr3; /* walks thought the buffer */
  long rows=0,mempool=0,i=0;
  int rra_index;
  xml_lc(buf); /* lets lowercase all active parts of the xml */
  ptr=buf;
  ptr2=buf;
  ptr3=buf;
  /* start with an RRD tag */

  eat_tag(&ptr,"rrd");
  /* allocate static header */
  if((rrd->stat_head = calloc(1,sizeof(stat_head_t)))==NULL){
    rrd_set_error("allocating rrd.stat_head");
    return -1;    
  };

  strcpy(rrd->stat_head->cookie,RRD_COOKIE);
  read_tag(&ptr,"version","%4[0-9]",rrd->stat_head->version);
  /* added primitive version checking */
  if (atoi(rrd -> stat_head -> version) > atoi(RRD_VERSION) )
  {
    rrd_set_error("Incompatible file version, detected version %s is bigger than supported version %s\n",
		  rrd -> stat_head -> version, RRD_VERSION );
    free(rrd -> stat_head);
    return -1;
  }
  if (atoi(rrd -> stat_head -> version) < 2) 
  {
    rrd_set_error("Can only restore version >= 2 (Not %s). Dump your old rrd using a current rrdtool dump.",  rrd -> stat_head -> version );
    free(rrd -> stat_head);
    return -1;
  }
  rrd->stat_head->float_cookie = FLOAT_COOKIE;
  rrd->stat_head->ds_cnt = 0;
  rrd->stat_head->rra_cnt = 0;
  read_tag(&ptr,"step","%lu",&(rrd->stat_head->pdp_step));

  /* allocate live head */
  if((rrd->live_head = calloc(1,sizeof(live_head_t)))==NULL){
    rrd_set_error("allocating rrd.live_head");
    return -1;    
  }
  read_tag(&ptr,"lastupdate","%lu",&(rrd->live_head->last_up));

  /* Data Source Definition Part */
  ptr2 = ptr;
  while (eat_tag(&ptr2,"ds") == 1){
      rrd->stat_head->ds_cnt++;
      if((rrd->ds_def = rrd_realloc(rrd->ds_def,rrd->stat_head->ds_cnt*sizeof(ds_def_t)))==NULL){
	  rrd_set_error("allocating rrd.ds_def");
	  return -1;
      };
      /* clean out memory to make sure no data gets stored from previous tasks */
      memset(&(rrd->ds_def[rrd->stat_head->ds_cnt-1]), 0, sizeof(ds_def_t));
      if((rrd->pdp_prep = rrd_realloc(rrd->pdp_prep,rrd->stat_head->ds_cnt
				  *sizeof(pdp_prep_t)))==NULL){
	rrd_set_error("allocating pdp_prep");
	return(-1);
      }
      /* clean out memory to make sure no data gets stored from previous tasks */
      memset(&(rrd->pdp_prep[rrd->stat_head->ds_cnt-1]), 0, sizeof(pdp_prep_t));

      read_tag(&ptr2,"name",DS_NAM_FMT,rrd->ds_def[rrd->stat_head->ds_cnt-1].ds_nam);

      read_tag(&ptr2,"type",DST_FMT,rrd->ds_def[rrd->stat_head->ds_cnt-1].dst);
      /* test for valid type */
      if( (int)dst_conv(rrd->ds_def[rrd->stat_head->ds_cnt-1].dst) == -1) return -1;      

	  if (dst_conv(rrd->ds_def[rrd->stat_head->ds_cnt-1].dst) != DST_CDEF)
	  {
      read_tag(&ptr2,"minimal_heartbeat","%lu",
	       &(rrd->ds_def[rrd->stat_head->ds_cnt-1].par[DS_mrhb_cnt].u_cnt));
      read_tag(&ptr2,"min","%lf",&(rrd->ds_def[rrd->stat_head->ds_cnt-1].par[DS_min_val].u_val));
      read_tag(&ptr2,"max","%lf",&(rrd->ds_def[rrd->stat_head->ds_cnt-1].par[DS_max_val].u_val));
	  } else { /* DST_CDEF */
		 char buffer[1024];
	     read_tag(&ptr2,"cdef","%s",buffer);
		 parseCDEF_DS(buffer,rrd,rrd -> stat_head -> ds_cnt - 1);
	  }

      read_tag(&ptr2,"last_ds","%30s",rrd->pdp_prep[rrd->stat_head->ds_cnt-1].last_ds);
      read_tag(&ptr2,"value","%lf",&(rrd->pdp_prep[rrd->stat_head->ds_cnt-1].scratch[PDP_val].u_val));
      read_tag(&ptr2,"unknown_sec","%lu",&(rrd->pdp_prep[rrd->stat_head->ds_cnt-1].scratch[PDP_unkn_sec_cnt].u_cnt));      
      eat_tag(&ptr2,"/ds");
      ptr=ptr2;
  }
  
  ptr2 = ptr;
  while (eat_tag(&ptr2,"rra") == 1){
      rrd->stat_head->rra_cnt++;

      /* allocate and reset rra definition areas */
      if((rrd->rra_def = rrd_realloc(rrd->rra_def,rrd->stat_head->rra_cnt*sizeof(rra_def_t)))==NULL){
	  rrd_set_error("allocating rra_def"); return -1; }      
      memset(&(rrd->rra_def[rrd->stat_head->rra_cnt-1]), 0, sizeof(rra_def_t));

      /* allocate and reset consolidation point areas */
      if((rrd->cdp_prep = rrd_realloc(rrd->cdp_prep,
				  rrd->stat_head->rra_cnt
				  *rrd->stat_head->ds_cnt*sizeof(cdp_prep_t)))==NULL){
	  rrd_set_error("allocating cdp_prep"); return -1; }

      memset(&(rrd->cdp_prep[rrd->stat_head->ds_cnt*(rrd->stat_head->rra_cnt-1)]), 
	     0, rrd->stat_head->ds_cnt*sizeof(cdp_prep_t));

      
      read_tag(&ptr2,"cf",CF_NAM_FMT,rrd->rra_def[rrd->stat_head->rra_cnt-1].cf_nam);
      /* test for valid type */
      if( (int)cf_conv(rrd->rra_def[rrd->stat_head->rra_cnt-1].cf_nam) == -1) return -1;

      read_tag(&ptr2,"pdp_per_row","%lu",&(rrd->rra_def[rrd->stat_head->rra_cnt-1].pdp_cnt));
      /* support to read RRA parameters */
      eat_tag(&ptr2, "params");
      skip(&ptr2);
      rra_index = rrd->stat_head->rra_cnt - 1;
      /* backwards compatibility w/ old patch */
      if (strncmp(ptr2, "<value>",7) == 0) {
         parse_patch1028_RRA_params(&ptr2,rrd,rra_index); 
      } else {
      switch(cf_conv(rrd -> rra_def[rra_index].cf_nam)) {
      case CF_HWPREDICT:
         read_tag(&ptr2, "hw_alpha", "%lf", 
            &(rrd->rra_def[rra_index].par[RRA_hw_alpha].u_val));
         read_tag(&ptr2, "hw_beta", "%lf", 
            &(rrd->rra_def[rra_index].par[RRA_hw_beta].u_val));
         read_tag(&ptr2, "dependent_rra_idx", "%lu", 
            &(rrd->rra_def[rra_index].par[RRA_dependent_rra_idx].u_cnt));
         break;
      case CF_SEASONAL:
      case CF_DEVSEASONAL:
         read_tag(&ptr2, "seasonal_gamma", "%lf", 
            &(rrd->rra_def[rra_index].par[RRA_seasonal_gamma].u_val));
         read_tag(&ptr2, "seasonal_smooth_idx", "%lu", 
            &(rrd->rra_def[rra_index].par[RRA_seasonal_smooth_idx].u_cnt));
         read_tag(&ptr2, "dependent_rra_idx", "%lu", 
            &(rrd->rra_def[rra_index].par[RRA_dependent_rra_idx].u_cnt));
         break;
      case CF_FAILURES:
         read_tag(&ptr2, "delta_pos", "%lf", 
            &(rrd->rra_def[rra_index].par[RRA_delta_pos].u_val));
         read_tag(&ptr2, "delta_neg", "%lf", 
            &(rrd->rra_def[rra_index].par[RRA_delta_neg].u_val));
         read_tag(&ptr2, "window_len", "%lu", 
            &(rrd->rra_def[rra_index].par[RRA_window_len].u_cnt));
         read_tag(&ptr2, "failure_threshold", "%lu", 
            &(rrd->rra_def[rra_index].par[RRA_failure_threshold].u_cnt));
         /* fall thru */
      case CF_DEVPREDICT:
         read_tag(&ptr2, "dependent_rra_idx", "%lu", 
            &(rrd->rra_def[rra_index].par[RRA_dependent_rra_idx].u_cnt));
         break;
      case CF_AVERAGE:
      case CF_MAXIMUM:
      case CF_MINIMUM:
      case CF_LAST:
      default:
         read_tag(&ptr2, "xff","%lf",
            &(rrd->rra_def[rra_index].par[RRA_cdp_xff_val].u_val));
      }
      }
      eat_tag(&ptr2, "/params");
      eat_tag(&ptr2,"cdp_prep");
      for(i=0;i< (int)rrd->stat_head->ds_cnt;i++)
      {
      eat_tag(&ptr2,"ds");
      /* support to read CDP parameters */
      rra_index = rrd->stat_head->rra_cnt-1; 
      skip(&ptr2);
      if (strncmp(ptr2, "<value>",7) == 0) {
         parse_patch1028_CDP_params(&ptr2,rrd,rra_index,i);
      } else {
         read_tag(&ptr2, "primary_value","%lf",
               &(rrd->cdp_prep[rrd->stat_head->ds_cnt*(rra_index)
               +i].scratch[CDP_primary_val].u_val));
         read_tag(&ptr2, "secondary_value","%lf",
               &(rrd->cdp_prep[rrd->stat_head->ds_cnt*(rra_index)
               +i].scratch[CDP_secondary_val].u_val));
         switch(cf_conv(rrd->rra_def[rra_index].cf_nam)) {
         case CF_HWPREDICT:
            read_tag(&ptr2,"intercept","%lf", 
               &(rrd->cdp_prep[rrd->stat_head->ds_cnt*(rra_index)
               +i].scratch[CDP_hw_intercept].u_val));
            read_tag(&ptr2,"last_intercept","%lf", 
               &(rrd->cdp_prep[rrd->stat_head->ds_cnt*(rra_index)
               +i].scratch[CDP_hw_last_intercept].u_val));
            read_tag(&ptr2,"slope","%lf", 
               &(rrd->cdp_prep[rrd->stat_head->ds_cnt*(rra_index)
               +i].scratch[CDP_hw_slope].u_val));
            read_tag(&ptr2,"last_slope","%lf", 
               &(rrd->cdp_prep[rrd->stat_head->ds_cnt*(rra_index)
               +i].scratch[CDP_hw_last_slope].u_val));
            read_tag(&ptr2,"nan_count","%lu", 
               &(rrd->cdp_prep[rrd->stat_head->ds_cnt*(rra_index)
               +i].scratch[CDP_null_count].u_cnt));
            read_tag(&ptr2,"last_nan_count","%lu", 
               &(rrd->cdp_prep[rrd->stat_head->ds_cnt*(rra_index)
               +i].scratch[CDP_last_null_count].u_cnt));
            break;
         case CF_SEASONAL:
         case CF_DEVSEASONAL:
            read_tag(&ptr2,"seasonal","%lf", 
               &(rrd->cdp_prep[rrd->stat_head->ds_cnt*(rra_index)
               +i].scratch[CDP_hw_seasonal].u_val));
            read_tag(&ptr2,"last_seasonal","%lf", 
               &(rrd->cdp_prep[rrd->stat_head->ds_cnt*(rra_index)
               +i].scratch[CDP_hw_last_seasonal].u_val));
            read_tag(&ptr2,"init_flag","%lu", 
               &(rrd->cdp_prep[rrd->stat_head->ds_cnt*(rra_index)
               +i].scratch[CDP_init_seasonal].u_cnt));
            break;
         case CF_DEVPREDICT:
            break;
         case CF_FAILURES:
            parse_FAILURES_history(&ptr2,rrd,rra_index,i); 
            break;
         case CF_AVERAGE:
         case CF_MAXIMUM:
         case CF_MINIMUM:
         case CF_LAST:
         default:
            read_tag(&ptr2,"value","%lf",&(rrd->cdp_prep[rrd->stat_head->ds_cnt
               *(rra_index) +i].scratch[CDP_val].u_val));
            read_tag(&ptr2,"unknown_datapoints","%lu",&(rrd->cdp_prep[rrd->stat_head->ds_cnt
               *(rra_index) +i].scratch[CDP_unkn_pdp_cnt].u_cnt));
            break;
	 }
      }
      eat_tag(&ptr2,"/ds");
      }
      eat_tag(&ptr2,"/cdp_prep");
      rrd->rra_def[rrd->stat_head->rra_cnt-1].row_cnt=0;
      eat_tag(&ptr2,"database");
      ptr3 = ptr2;      
      while (eat_tag(&ptr3,"row") == 1){
	
	  if(mempool==0){
	    mempool = 1000;
	    if((rrd->rrd_value = rrd_realloc(rrd->rrd_value,
					 (rows+mempool)*(rrd->stat_head->ds_cnt)
					 *sizeof(rrd_value_t)))==NULL) {
	      rrd_set_error("allocating rrd_values"); return -1; }
	  }
	  rows++;
	  mempool--;
	  rrd->rra_def[rrd->stat_head->rra_cnt-1].row_cnt++;
	  for(i=0;i< (int)rrd->stat_head->ds_cnt;i++){

		  rrd_value_t  * value = &(rrd->rrd_value[(rows-1)*rrd->stat_head->ds_cnt+i]);

		  read_tag(&ptr3,"v","%lf", value);
		  
		  if (
			  (rc == 1)			/* do we have to check for the ranges */
			  &&
		      (!isnan(*value))	/* not a NAN value */
		      &&
			  (dst_conv(rrd->ds_def[i].dst) != DST_CDEF)
			  &&
		      (					/* min defined and in the range ? */
			  (!isnan(rrd->ds_def[i].par[DS_min_val].u_val) 
			  	&& (*value < rrd->ds_def[i].par[DS_min_val].u_val)) 
			  ||				/* max defined and in the range ? */
			  (!isnan(rrd->ds_def[i].par[DS_max_val].u_val) 
			  	&& (*value > rrd->ds_def[i].par[DS_max_val].u_val))
		      )
		  ) {
		      fprintf (stderr, "out of range found [ds: %lu], [value : %0.10e]\n", i, *value);
		      *value = DNAN;
		  }
	  }
      	  eat_tag(&ptr3,"/row");                  
	  ptr2=ptr3;
      }
      eat_tag(&ptr2,"/database");
      eat_tag(&ptr2,"/rra");                  
      ptr=ptr2;
  }  
  eat_tag(&ptr,"/rrd");

  if((rrd->rra_ptr = calloc(1,sizeof(rra_ptr_t)*rrd->stat_head->rra_cnt)) == NULL) {
      rrd_set_error("allocating rra_ptr");
      return(-1);
  }

  for(i=0; i < (int)rrd->stat_head->rra_cnt; i++) {
	  /* last row in the xml file is the most recent; as
	   * rrd_update increments the current row pointer, set cur_row
	   * here to the last row. */
      rrd->rra_ptr[i].cur_row = rrd->rra_def[i].row_cnt-1;
  }
  if (ptr==NULL)
      return -1;
  return 1;
}
Ejemplo n.º 26
0
// copy real tag to vtag or set up emulation
BOOL vtag_copy_from_tag(BYTE *tagtype, BYTE *pass)
{
    BYTE tmp[MAXUID + 1], tag, copy= FALSE, i;
    unsigned int config_block_no, user_block_no;

    // set target tag type
    if (strlen(tagtype) == 0)
    {
        if(RFIDlerVTag.TagType == TAG_TYPE_NONE)
            tag= RFIDlerConfig.TagType;
        else
            tag= RFIDlerVTag.TagType;
    }
    else
        if(!(tag= tag_get_type(tagtype)))
            return FALSE;
    
    // check we've got a tag to copy
    if(!get_tag_uid(tmp))
        return FALSE;

    // set vtag to desired type
    vtag_set_tag_from_type(tag);

    // if tag & vtag are the same, just copy
    if(RFIDlerConfig.TagType == tag)
    {
        RFIDlerVTag.EmulatedTagType= TAG_TYPE_NONE;
        // auth
        if(!tag_login(0, TmpBits, pass))
            tag_auth(0, TmpBits, pass);

        // copy UID
        strcpy(RFIDlerVTag.UID, tmp);
        
        // if no data to copy, we're done.
        if(RFIDlerVTag.DataBlocks == 0)
            return TRUE;

        // copy data blocks
        for(i= 0 ; i < RFIDlerVTag.DataBlocks ; ++i)
        {
            if (!read_tag(RFIDlerVTag.Data + HEXDIGITS(i * RFIDlerVTag.BlockSize), i, i))
                UserMessageNum("%d: (fail)\r\n", i);
            else
                copy= TRUE;
        }
        return copy;
    }

    // otherwise, set up emulation
    RFIDlerVTag.EmulatedTagType= RFIDlerConfig.TagType;
    strcpy(RFIDlerVTag.UID, tmp);

    // get config & user data block numbers
    if(!config_block_number(&config_block_no, tag) || !config_user_block(&user_block_no, tag))
        return FALSE;

    // get & store config block
    if (!config_block(&RFIDlerVTag.Data[HEXDIGITS(RFIDlerVTag.BlockSize * config_block_no)], RFIDlerConfig.TagType, tag))
        return FALSE;

    // copy raw hex UID to data blocks
    memcpy(&RFIDlerVTag.Data[HEXDIGITS(RFIDlerVTag.BlockSize * user_block_no)], RFIDlerVTag.UID, strlen(RFIDlerVTag.UID));

    return TRUE;
}
Ejemplo n.º 27
0
Archivo: s98d.c Proyecto: autch/s98ml
int main(int ac, char** av)
{
    struct s98context context;
    struct s98context* ctx = &context;
    struct s98header* h = &context.header;
    FILE* fp;

    if(ac != 2) {
        fprintf(stderr, "Usage: %s filename.s98\n", *av);
        return 1;
    }

    fp = fopen(*++av, "rb");
    if(fp == NULL) {
        perror(*av);
        return -1;
    }

    memset(ctx, 0, sizeof context);

    fseek(fp, 0, SEEK_END);
    ctx->s98_size = ftell(fp);
    ctx->s98_buffer = malloc(ctx->s98_size);

    rewind(fp);
    fread(ctx->s98_buffer, 1, ctx->s98_size, fp);
    set_offset(ctx, 0);
    fclose(fp);

    if(read_header(ctx) != 0)
        goto cleanup;
    read_devices(ctx);

    printf("; S98 File: %s\n", *av);
    printf("; Offset to tag: 0x%08x (0 if none)\n", h->offset_to_tag);
    printf("; Dump start: 0x%08x\n", h->offset_to_dump);
    printf("; Loop start: 0x%08x (0 if non-looped)\n", h->offset_to_loop);

    printf("#version %d\n", h->version);
    printf("#timer %d/%d\n", h->timer_numerator, h->timer_denominator);

    read_tag(ctx);

    putchar('\n');
    {
        int i;
        for(i = 0; i < h->device_count; i++) {
            struct s98deviceinfo* info;
            info = ctx->devices + i;

            printf("#device %s %d $%02x\n", device_name(info->device), info->clock, info->panpot);
        }
    }

    putchar('\n');

    s98d_dump(ctx);

    putchar('\n');


cleanup:
    free_context(&context);

    return 0;
}