예제 #1
0
void ipv6loganon_printinfo(void)  {
	printversion();
	printcopyright();
	fprintf(stderr, "This program anonymizes IPv4/IPv6 addresses in HTTP server log files\n");
	fprintf(stderr, "See '%s -?' for more details\n\n", PROGRAM_NAME);
};
예제 #2
0
파일: pipictest.c 프로젝트: oh7bf/PiPIC
int main(int argc, char **argv)
{  
  int verb=0; // 1=verbosed output
  int testi2c=0; // test i2c data flow 
  int ccycle=0; // count clock cycles
  int analog0=0; // read in AN0 analog voltage
  int analog1=0; // read in AN1 analog voltage
  int analog3=0; // read in AN3 analog voltage
  int fd;
  char fileName[100]="/dev/i2c-1";
  int  address=0x00;
  unsigned char buf[10];
  unsigned char send[10];
  int i=0,j=0;
  int errcnt=0; // error count
  int nrpt=1; // number of times to repeate test function
  int rtime=0; // cycle time from PIC
  int t1=0,t2=0,dt=0; // start and end time of cycle count
  int ain0=0,ain1=0,ain3=0; // analog input voltage

  int optch=0;
  while(optch!=-1)
    {
      optch=getopt(argc,argv,"a:n:i013chvV");
      if(optch=='a')
	{
	  sscanf(optarg,"%X",&address);
	}
      if(optch=='n')
	{
	  nrpt=atoi(optarg); 
	}
      if(optch=='i')
	{
          testi2c=1;          
	}
      if(optch=='c')
	{
          ccycle=1;          
	}
      if(optch=='0')
	{
          analog0=1;          
	}
      if(optch=='1')
	{
          analog1=1;          
	}
      if(optch=='3')
	{
          analog3=1;          
	}
      if(optch=='v')
	{
          verb=1;
	}
      if(optch=='h')
	{
	  printusage();
	  return 0;
	}
      if(optch=='V')
	{
	  printversion();
	  return 0;
	}
    }

  if((address<0x03)||(address>0x77))
    {
      printusage();
      return -1;
    }

// open port for reading and writing
  if(verb==1) printf("Open %s\n", fileName);
  if((fd = open(fileName, O_RDWR)) < 0) 
  {
     perror("Failed to open i2c port");
     return -1;
  }

  if(verb==1) printf("Chip address 0x%02x\n", address);
  if(ioctl(fd, I2C_SLAVE, address) < 0) 
  {
     perror("Unable to get bus access to talk to slave");
     return -1;
  }

  if((verb==1)&&(testi2c==1)) printf("                    send         received\n"); 
  if(ccycle==1)
  {
     printf("reset timer\n");
     t1=printime();
     buf[0]=0x50; // reset PIC timer
     if((write(fd, buf, 1)) != 1) 
     {
          perror("Error writing to i2c slave");
          return -1;
     }
     printf("cycles\n");
  } 

  srand((unsigned int)time(NULL));
  for(j=0;j<nrpt;j++)
  {
     if(testi2c==1)
     {
        if(verb==1) printime();
        errcnt=0;
        for(i=0;i<4;i++)
        {
           buf[i+1]=rand();
           send[i]=buf[i+1];
        }
        buf[0]=2;
        if(verb==1) 
        {
           printf("0x%02x%02x%02x%02x",buf[1],buf[2],buf[3],buf[4]);
           printf("   ");
        }
        if((write(fd, buf, 5)) != 5) 
        {
           perror("Error writing to i2c slave");
           return -1;
        }
        if(read(fd, buf,4)!=4) 
        {
           perror("Unable to read from slave");
           return -1;
        }
        else 
        {
           if(verb==1)printf("0x%02x%02x%02x%02x\n",buf[0],buf[1],buf[2],buf[3]); 
           if((send[0]!=buf[0])||(send[1]!=buf[1])||(send[2]!=buf[2])||(send[3]!=buf[3])) 
           {
              printime();
              printf("0x%02x%02x%02x%02x",send[0],send[1],send[2],send[3]);
              printf(" !=");
              printf("0x%02x%02x%02x%02x\n",buf[0],buf[1],buf[2],buf[3]); 
              errcnt++;
           }
        }
     }

     if(ccycle==1)
     {
        if(verb==1) t2=printime();
        buf[0]=0x51;
        if((write(fd, buf, 1)) != 1) 
        {
           perror("Error writing to i2c slave");
           return -1;
        }
        if(read(fd, buf,4)!=4) 
        {
           perror("Unable to read from slave");
           return -1;
        }
        else 
        {
           if(verb==1)printf("0x%02x%02x%02x%02x ",buf[0],buf[1],buf[2],buf[3]); 
           rtime=16777216*buf[0]+65536*buf[1]+256*buf[2]+buf[3];
           if(verb==1) printf ("%d\n",rtime);
        }
     }

     if((analog0==1)||(analog1==1)||(analog3==1)) t2=printime();
     if(analog0==1)
     {
        buf[0]=0x40;
        if((write(fd, buf, 1)) != 1) 
        {
           perror("Error writing to i2c slave");
           return -1;
        }
        if(read(fd, buf,2)!=2) 
        {
           perror("Unable to read from slave");
           return -1;
        }
        else 
        {
           if(verb==1)printf("0x%02x%02x ",buf[0],buf[1]);
           ain0=256*buf[0]+buf[1];
           printf ("%d ",ain0);
        }
     }

     if(analog1==1)
     {
        buf[0]=0x41;
        if((write(fd, buf, 1)) != 1) 
        {
           perror("Error writing to i2c slave");
           return -1;
        }
        if(read(fd, buf,2)!=2) 
        {
           perror("Unable to read from slave");
           return -1;
        }
        else 
        {
           if(verb==1)printf("0x%02x%02x ",buf[0],buf[1]);
           ain1=256*buf[0]+buf[1];
           printf ("%d ",ain1);
        }
     }

     if(analog3==1)
     {
        buf[0]=0x43;
        if((write(fd, buf, 1)) != 1) 
        {
           perror("Error writing to i2c slave");
           return -1;
        }
        if(read(fd, buf,2)!=2) 
        {
           perror("Unable to read from slave");
           return -1;
        }
        else 
        {
           if(verb==1)printf("0x%02x%02x ",buf[0],buf[1]);
           ain3=256*buf[0]+buf[1];
           printf ("%d ",ain3);
        }
     }

     if((analog0==1)||(analog1==1)||(analog3==1)) printf("\n");

  }

  if(ccycle==1)
  {
    t2=printime();
    dt=t2-t1;
    printf("elapsed seconds %d for %d cycles\n",dt,rtime);
    if(dt>0) printf("%f s/cycle\n",((float)dt)/((float)rtime));
  }
  
  if(testi2c==1) printf("i2c errors %d\n",errcnt);

  return 0;
}
예제 #3
0
파일: brandelf.c 프로젝트: flyrain/elftool
int
main(int argc, char **argv)
{
	GElf_Ehdr ehdr;
	Elf *elf;
	Elf_Kind kind;
	int type = ELFOSABI_NONE;
	int retval = 0;
	int ch, change = 0, verbose = 0, force = 0, listed = 0;

	if (elf_version(EV_CURRENT) == EV_NONE)
		errx(EXIT_FAILURE, "elf_version error");

	while ((ch = getopt_long(argc, argv, "Vf:hlt:v", brandelf_longopts,
		NULL)) != -1)
		switch (ch) {
		case 'f':
			if (change)
				errx(EXIT_FAILURE, "ERROR: the -f option is "
				    "incompatible with the -t option.");
			force = 1;
			type = atoi(optarg);
			if (errno == ERANGE || type < 0 || type > 255) {
				warnx("ERROR: invalid argument to option "
				    "-f: %s", optarg);
				usage();
			}
			break;
		case 'h':
			usage();
			break;
		case 'l':
			printelftypes();
			listed = 1;
			break;
		case 'v':
			verbose = 1;
			break;
		case 't':
			if (force)
				errx(EXIT_FAILURE, "the -t option is "
				    "incompatible with the -f option.");
			if ((type = elftype(optarg)) == -1) {
				warnx("ERROR: invalid ELF type '%s'", optarg);
				usage();
			}

			change = 1;
			break;
		case 'V':
			printversion();
			break;
		default:
			usage();
	}
	argc -= optind;
	argv += optind;
	if (!argc) {
		if (listed)
			exit(0);
		else {
			warnx("no file(s) specified");
			usage();
		}
	}

	while (argc) {
		int fd;

		elf = NULL;

		if ((fd = open(argv[0], (change || force) ? O_RDWR :
		    O_RDONLY, 0)) < 0) {
			warn("error opening file %s", argv[0]);
			retval = 1;
			goto fail;
		}

		if ((elf = elf_begin(fd, (change || force) ? ELF_C_RDWR :
		    ELF_C_READ, NULL)) == NULL) {
			warnx("elf_begin failed: %s", elf_errmsg(-1));
			retval = 1;
			goto fail;
		}

		if ((kind = elf_kind(elf)) != ELF_K_ELF) {
			if (kind == ELF_K_AR)
				warnx("file '%s' is an archive.", argv[0]);
			else
				warnx("file '%s' is not an ELF file.",
				    argv[0]);
			retval = 1;
			goto fail;
		}

		if (gelf_getehdr(elf, &ehdr) == NULL) {
			warnx("gelf_getehdr: %s", elf_errmsg(-1));
			retval = 1;
			goto fail;
		}

		if (!change && !force) {
			fprintf(stdout,
			    "File '%s' is of brand '%s' (%u).\n",
			    argv[0], iselftype(ehdr.e_ident[EI_OSABI]),
			    ehdr.e_ident[EI_OSABI]);
			if (!iselftype(type)) {
				warnx("ELF ABI Brand '%u' is unknown",
				      type);
				printelftypes();
			}
		} else {

			/*
			 * Keep the existing layout of the ELF object.
			 */
			if (elf_flagelf(elf, ELF_C_SET, ELF_F_LAYOUT) == 0) {
				warnx("elf_flagelf failed: %s",
				    elf_errmsg(-1));
				retval = 1;
				goto fail;
			}

			/*
			 * Update the ABI type.
			 */
			ehdr.e_ident[EI_OSABI] = type;
			if (gelf_update_ehdr(elf, &ehdr) == 0) {
				warnx("gelf_update_ehdr error: %s",
				    elf_errmsg(-1));
				retval = 1;
				goto fail;
			}

			/*
			 * Write back changes.
			 */
			if (elf_update(elf, ELF_C_WRITE) == -1) {
				warnx("elf_update error: %s", elf_errmsg(-1));
				retval = 1;
				goto fail;
			}
		}
fail:

		if (elf)
			elf_end(elf);

		if (fd >= 0 && close(fd) == -1) {
			warnx("%s: close error", argv[0]);
			retval = 1;
		}

		argc--;
		argv++;
	}

	return (retval);
}
예제 #4
0
/* test program for minissdpd */
int
main(int argc, char * * argv)
{
	const char command0[] = { 0x00, 0x00 };
	char command1[] = "\x01\x00urn:schemas-upnp-org:device:InternetGatewayDevice";
	char command2[] = "\x02\x00uuid:fc4ec57e-b051-11db-88f8-0060085db3f6::upnp:rootdevice";
	const char command3[] = { 0x03, 0x00 };
	/* old versions of minissdpd would reject a command with
	 * a zero length string argument */
	char command3compat[] = "\x03\x00ssdp:all";
	char command4[] = "\x04\x00test:test:test";
	const char bad_command[] = { 0xff, 0xff };
	const char overflow[] = { 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
	const char command5[] = { 0x05, 0x00 };
	const char bad_command4[] = { 0x04, 0x01, 0x60, 0x8f, 0xff, 0xff, 0xff, 0x7f};
	int s;
	int i;
	void * tmp;
	unsigned char * resp = NULL;
	size_t respsize = 0;
	unsigned char buf[4096];
	ssize_t n;
	int total = 0;
	const char * sockpath = "/var/run/minissdpd.sock";

	for(i=0; i<argc-1; i++) {
		if(0==strcmp(argv[i], "-s"))
			sockpath = argv[++i];
	}
	command1[1] = sizeof(command1) - 3;
	command2[1] = sizeof(command2) - 3;
	command3compat[1] = sizeof(command3compat) - 3;
	command4[1] = sizeof(command4) - 3;
	s = connect_unix_socket(sockpath);

	n = SENDCOMMAND(command0, sizeof(command0));
	n = read(s, buf, sizeof(buf));
	printf("Response received %d bytes\n", (int)n);
	if(n > 0) {
		printversion(buf, n);
	} else {
		printf("Command 0 (get version) not supported\n");
		close(s);
		s = connect_unix_socket(sockpath);
	}

	n = SENDCOMMAND(command1, sizeof(command1) - 1);
	n = read(s, buf, sizeof(buf));
	printf("Response received %d bytes\n", (int)n);
	printresponse(buf, n);
	if(n == 0) {
		close(s);
		s = connect_unix_socket(sockpath);
	}

	n = SENDCOMMAND(command2, sizeof(command2) - 1);
	n = read(s, buf, sizeof(buf));
	printf("Response received %d bytes\n", (int)n);
	printresponse(buf, n);
	if(n == 0) {
		close(s);
		s = connect_unix_socket(sockpath);
	}

	buf[0] = 0; /* Slight hack for printing num devices when 0 */
	n = SENDCOMMAND(command3, sizeof(command3));
	n = read(s, buf, sizeof(buf));
	if(n == 0) {
		printf("command3 failed, testing compatible one\n");
		close(s);
		s = connect_unix_socket(sockpath);
		n = SENDCOMMAND(command3compat, sizeof(command3compat) - 1);
		n = read(s, buf, sizeof(buf));
	}
	printf("Response received %d bytes\n", (int)n);
	printf("Number of devices %d\n", (int)buf[0]);
	while(n > 0) {
		tmp = realloc(resp, respsize + n);
		if(tmp == NULL) {
			fprintf(stderr, "memory allocation error\n");
			break;
		}
		resp = tmp;
		respsize += n;
		if (n > 0) {
			memcpy(resp + total, buf, n);
			total += n;
		}
		if (n < (ssize_t)sizeof(buf)) {
			break;
		}

		n = read(s, buf, sizeof(buf));
		printf("response received %d bytes\n", (int)n);
	}
	if(resp != NULL) {
		printresponse(resp, total);
		free(resp);
		resp = NULL;
	}
	if(n == 0) {
		close(s);
		s = connect_unix_socket(sockpath);
	}

	n = SENDCOMMAND(command4, sizeof(command4));
	/* no response for request type 4 */

	n = SENDCOMMAND(bad_command, sizeof(bad_command));
	n = read(s, buf, sizeof(buf));
	printf("Response received %d bytes\n", (int)n);
	printresponse(buf, n);
	if(n == 0) {
		close(s);
		s = connect_unix_socket(sockpath);
	}

	n = SENDCOMMAND(overflow, sizeof(overflow));
	n = read(s, buf, sizeof(buf));
	printf("Response received %d bytes\n", (int)n);
	printresponse(buf, n);
	if(n == 0) {
		close(s);
		s = connect_unix_socket(sockpath);
	}

	n = SENDCOMMAND(command5, sizeof(command5));
	n = read(s, buf, sizeof(buf));
	printf("Response received %d bytes\n", (int)n);
	printresponse(buf, n);
	if(n == 0) {
		close(s);
		s = connect_unix_socket(sockpath);
	}

	n = SENDCOMMAND(bad_command4, sizeof(bad_command4));
	n = read(s, buf, sizeof(buf));
	printf("Response received %d bytes\n", (int)n);
	printresponse(buf, n);

	close(s);
	return 0;
}
예제 #5
0
int main(int argc, char *argv[])
{
	int i=0,debug=0,r,j=0,x=0,selected=-1;
	long int gi=0,gf=0;
        int colord=66,colorg=71;
        struct dirent **namelist;
        int ls=0,metnum=0;
        unsigned char buf[516] ;
	char * tmpdir = NULL;
        for (i=1; i<argc; i++) {
	        char *arg = argv[i];
                if (*arg=='-') {
                        switch (arg[1]) {
	                        case 't' :
					tmpdir = argv[i+1];
					printf("Using temp dir %s\n",tmpdir);
                                break;
	                        case 'w' :
				     if (argc>i+1){
					if (!strcasecmp(argv[i+1],"red")) colord=71;
					else if (!strcasecmp(argv[i+1],"blue")) colord=76;
					else if (!strcasecmp(argv[i+1],"yellow")) colord=81;
					else if (!strcasecmp(argv[i+1],"white")) colord=86;
					else if (!strcasecmp(argv[i+1],"cyan")) colord=91;
					else if (!strcasecmp(argv[i+1],"black")) colord=96;
					else if (!strcasecmp(argv[i+1],"blank")) colord=101;
					else printf("Invalid color %s\n",argv[i+1]);
				     }else {usage();exit(-1);}
                                break;
	                        case 'g' :
				     if (argc>i+1){
					if (!strcasecmp(argv[i+1],"green")) colorg=66;
					else if (!strcasecmp(argv[i+1],"blue")) colorg=76;
					else if (!strcasecmp(argv[i+1],"yellow")) colorg=81;
					else if (!strcasecmp(argv[i+1],"white")) colorg=86;
					else if (!strcasecmp(argv[i+1],"cyan")) colorg=91;
					else if (!strcasecmp(argv[i+1],"black")) colorg=96;
					else if (!strcasecmp(argv[i+1],"blank")) colorg=101;
					else printf("Invalid color %s\n",argv[i+1]);
				     }else {usage();exit(-1);}
                                break;
	                        case 'v' :
	                                printversion();
	                                exit(0);
                                break;
	                        case 'd' :
	                                debug=1;
	                                printf("Debuggin mode: \n");
                                break;
	                        default:
	                                usage();
	                                exit(0);
	                         break;
	               }
	       }
	}
	if (!tmpdir) { usage(); exit(-1);}

	openXwindow(argc, argv, wmdonkeymon_master_xpm, wmdonkeymon_mask_bits, wmdonkeymon_mask_width, wmdonkeymon_mask_height);
		copyXPMArea(5,60,52,54,5,3);
		RedrawWindow();
		splash();


	r = 0;
	while (1) {
         if (!r) {
	        FILE * met;
	        unsigned char type;
	        short int len=0,vlen=0;
	        int gaps=0, firstgap = 0x7fffffff,  miss=0, fsize=0,metcount=0;
	        long int fileSize=0, num =0;
	        char nvalue[516],value[516];
		j =0;
		metnum=0;
		// Search for files in temp directory
		ls = scandir(tmpdir, &namelist, 0, alphasort);
		if (ls < 0){
		      printf("Can't find files in %s",tmpdir);
		      exit(-1);
		}
	        else {
		      while(ls-- && (metcount<4)) {
			    char * pt;
			    pt = strstr(namelist[ls]->d_name,".part.met");
			    if (pt && !strcmp(pt,".part.met")) {
				    if(debug)printf("File: %s\n",namelist[ls]->d_name);
				    strcpy(files[metcount].metname,namelist[ls]->d_name);
				    metcount++;
	  	    	    }
		           free(namelist[ls]);
		      }
		      free(namelist);
		}
		for (metnum=0; metnum < metcount; metnum++)	{
			i=0;
			sprintf(buf,"%s%s",tmpdir,files[metnum].metname);
			files[metnum].t_miss=0;
			if(debug)printf("opening %s\n",buf);
		        if ( (met = fopen(buf,"rb")) != NULL) {}
		        else {printf("Nada\n");};

		        // Version
		        i += fread(buf,1,1,met);
		        if(debug){ printf("Version: %x\n",buf[0]); }

			// Date ??
		        i += fread(buf,1,4,met);
		        if(debug) { printf("Date: %x %x %x %x \n",buf[0],buf[1],buf[2],buf[3]); }

			// Hash
		        i += fread(buf,1,16,met);
		        if(debug){ printf("Hash: ");  for (j=0;j<16;j++)  printf("%x ",buf[j]); 	 printf("\n");  }


			// Partial Hashes
		        i += fread(buf,1,2,met);
		        memcpy(&j,buf,2);
		        if(debug)  printf("Num of Hashes: %d\n",j);

			// Hashes
		        for (i=0;i<j;i++){
		              fread(buf,1,16,met);
		              if(debug){printf("Hash %d: ",i+1);    for (x=0;x<16;x++) printf("%x ",buf[x]);     printf("\n");}
		       }

		        // Num of Meta Tags
		        i = fread(buf,1,4,met);
		        memcpy(&num,buf,4);
		        if(debug){printf("Num of Meta Tags: %ld\n",num);}
		        x = 0;

			// Meta Tags
			for (i=0;i<num;i++){
				fread(&type,1,1,met);
				fread(&len,2,1,met);
				fread(nvalue,1,len,met);
				if (type==2){
				    // String Tag
				    fread(&vlen,1,2,met);
				    fread(value,1,vlen,met);
				    value[vlen] = '\0';
				    if (len==1){
					    // Special Tag
					     switch (nvalue[0]){
					       case 1:
						    strcpy(files[metnum].name,value);
						    if(debug){printf("File Name: %s\n",value);}
					       break;
					       case 3:
						    if(debug){printf("File Type: %s\n",value);}
						    strcpy(files[metnum].type,value);
					       break;
					       case 4:
						    if(debug){printf("File Format: %s\n",value);}
					       break;
					       case 18:
						    if(debug){printf("Temp file: %s\n",value);}
					       break;

					     }

				    } else if (debug)printf("Unknow String Tag %d: %s",nvalue[0],value);
				}else	if (type==3){
				    fread(&fsize,1,4,met);
				    if (len==1){
				    	// Special Tag
					    switch (nvalue[0]){
					       case 2:
					      	    if(debug)printf("File Size: %d KB\n",fsize/(1024));
						    fileSize = fsize;
					       break;
					       case 8:
					      	    if(debug)printf("Copied so Far: %d KB\n",fsize/(1024));
						    files[metnum].copied=fsize;
					       break;
					       case 19:
					      	   if(debug) printf("Priority: %d\n",fsize);
					       break;
					       case 20:
					      	    if(debug)printf("Status: %d\n",fsize);
						    files[metnum].status = fsize;
					       break;
					       default:
					       	   if(debug)printf("Unknow Tag %d: %d\n",nvalue[0],fsize);
					       break;
					    }
				    } else {
				    	    if (nvalue[0]==9){
						    nvalue[len]='\0';
						    if(debug)printf("gap %3s from %10d", &nvalue[1], fsize);
						    gaps = fsize;
						    if (gaps < firstgap) firstgap = gaps;
					    }else if (nvalue[0]==10){
						   miss = fsize - gaps;
						   gi = (long int)((SLOT_SIZE * (gaps/1024)) / (fileSize/1024));
						   gf = (long int)((SLOT_SIZE * (fsize/1024)) / (fileSize/1024));
						   if (gf>=gi){
						   	files[metnum].gappos[x][0] = gi;
							files[metnum].gappos[x][1] = gf;
							x++;
						   }
						   files[metnum].t_miss += miss;
					    	   if(debug)printf(" to %10d = %10d  Size(%d) Gaprel: %d-%d\n",fsize,miss,9728000,files[metnum].gappos[x][0],files[metnum].gappos[x][1]);
					    }
		                   }

			     }
		        }

		files[metnum].gapnum = x;
		files[metnum].firstgap = firstgap;
		files[metnum].lastsize = files[metnum].copied;
		files[metnum].size = fileSize;

	// sort gaps
	/*	don'n needed
	 * 	for (i=0; i<x; i++)
			 for (j=0; j<x; j++) {
			 	if (files[0].gappos[i][0]<files[0].gappos[j][0]) {
					z = files[0].gappos[i][0];
					files[0].gappos[i][0] = files[0].gappos[j][0];
					files[0].gappos[j][0] = z;
					z = files[0].gappos[i][1];
					files[0].gappos[i][1] = files[0].gappos[j][1];
					files[0].gappos[j][1] = z;
				}
			 }
		if(debug)for (i=0; i<x; i++){	printf("[%d-%d]",files[0].gappos[i][0],files[0].gappos[i][1]);	}
	*/

		if(debug)printf("%d bytes = %.2f mb missing\n", files[metnum].t_miss, (double)files[metnum].t_miss/(1024*1024));
		if(debug)if (firstgap < 0x7fffffff) printf("first gap starts at %d (%d blocks are complete)\n", firstgap, firstgap/(9500*1024));


		fclose(met);
	     }
	}



		while (XPending(display)) {
			XNextEvent(display, &Event);
			switch (Event.type) {
			case Expose:
				RedrawWindow();
				break;
                        case ButtonPress:
                                but_stat = CheckMouseRegion(Event.xbutton.x, Event.xbutton.y);
                        	break;
	                case ButtonRelease:
	                        i = CheckMouseRegion(Event.xbutton.x, Event.xbutton.y);
	                        if (but_stat == i && but_stat >= 0) {
					if (selected>-1) selected=-1;
					else selected=i;
	                         }
				break;
			}
		}

		for (j=0;j<15;j++) DelMouseRegion(j);

		if (metnum==0){
			splash();
			showString("NO FILES",8);
			showString("FOUND IN",9);
			showString("TEMP DIR",10);
		}else if (selected>-1){
			char out[30];
			char unit[4] = " KMG";
			long int s,c;
			int sk=0,ck=0;
			copyXPMArea(5,60,52,54,5,3);
			AddMouseRegion(0,5,5,54,54);
			showString(files[selected].name,1);

			s=files[selected].size;
			while (s>1024){s/=1024;sk++;}
			c=files[selected].copied;
			while (c>1024){c/=1024;ck++;}

			sprintf(out,"%ld%c/%ld%c",c,unit[ck],s,unit[sk]);
			showString(out,4);

			sprintf(out,"%s",files[selected].type);
			showString(out,5);

			// **************
			// Donwload Rate
			// Don't work unless edonkey update met files more frequently
			//
			//  s = (files[selected].copied) - (files[selected].lastsize);
			//  sprintf(out,"%ld B/S",(s/REF_RATE));
			//  showString(out,8);

			//************************
			//STATUS
			//status tag is always "Looking..."      :(
			//
			//getStatus(files[selected].status,out);
			//showString(out,9);
			sprintf(out,"%.3f%%", (( 1.0 *  files[selected].copied / files[selected].size))*100);
			showString(out,8);

			copyXPMArea(66,colord,52,5,5,11);
			for (i=0; i < files[selected].gapnum ; i++) {
				copyXPMArea(66,colorg,files[selected].gappos[i][1]-files[selected].gappos[i][0],5,files[selected].gappos[i][0]+5 ,11);
			}
		}else{
			copyXPMArea(5,60,52,54,5,3);
			for (j=0; j<metnum; j++){
			        showString(files[j].name,(j*2)+1+j);
				copyXPMArea(66,colord,52,5,5,(j+1)*10+(j*5) );
//				printf("top: %d\n",((j+1)*10+(j*5)));
				for (i=0; i < files[j].gapnum ; i++) {
					copyXPMArea(66,colorg,files[j].gappos[i][1]-files[j].gappos[i][0],5,files[j].gappos[i][0]+5 ,(j+1)*10+(j*5));
				}
				AddMouseRegion(j,5,(j+1)*5,52,(j+1)*10+(j*5)+5);
			}
		}
		RedrawWindow();

		sleep(1);
      		r++;
		if (r==REF_RATE) r=0;

    }
}
예제 #6
0
int main(int argc, char *argv[]) {
	int want_dump=0;
	int lport;
	int sock, n, i;
	size_t length, fromlen;
	struct sockaddr_in addr;
	struct sockaddr_in from;
	char buf[BUFSIZ];

	remoteconnection *rc = NULL; 

	if (argc == 2) {
		if (!strcmp(argv[1], "-V") || !strcmp(argv[1], "--version")) {
			printversion(argv[0]);
			return (0);
		}
		if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
				usage (argv[0], 0);
		}
	}

	if (argc < 2)
		usage(argv[0], 1);

	lport = atoi(argv[1]);
	rc=calloc((argc-2), sizeof(remoteconnection));

	if (argc == 2) {
		want_dump = 1;	
		//printf("raw data dump mode!\n");
	}
	for (i=2; i < argc; i++) {
		char *hostname=NULL;
		int port=0;
		if(!splithp(argv[i], &hostname, &port)) {
			open_rc(&(rc[(i-2)]), hostname, port);
			rc[(i-2)].port=port;
			rc[(i-2)].hostname=hostname;
			//printf(" dup to h:%s p:%i\n", hostname, port);
		}
	}

	sock=socket(AF_INET, SOCK_DGRAM, 0);
	if (sock < 0)
		error("Opening socket");

	setnonblock(sock, 1);

	int val=1;
#ifndef HAVE_WINDOWS
	setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val,  sizeof(int));
#else
	setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &val,  sizeof(int));
#endif

	length = sizeof(addr);
	bzero(&addr, length);
	addr.sin_family=AF_INET;
	addr.sin_addr.s_addr=INADDR_ANY;
	addr.sin_port=htons(lport);
	if (bind(sock, (struct sockaddr *)&addr, length)<0)
		error("binding to port %i failed.", lport);
	fromlen = sizeof(struct sockaddr_in);

	run=1;
#ifndef HAVE_WINDOWS
	signal (SIGHUP, catchsig);
	signal (SIGINT, catchsig);
#endif

	while (run) {
    fd_set rfds;
    struct timeval tv;
    tv.tv_sec = 1; tv.tv_usec = 0;

    FD_ZERO(&rfds);
    FD_SET(sock, &rfds);
    if((select(sock+1, &rfds, NULL, NULL, &tv))<0) {
      if (errno!=EINTR) {
        break;
			}
			continue;
    }
    if(!FD_ISSET(sock, &rfds)) 
			continue;

		n = recvfrom(sock, buf, BUFSIZ, 0, (struct sockaddr *)&from, &fromlen);
		if (n < 0)
			error("recvfrom");
		if (want_dump) {
			//printf("Received a datagram: ");
			write(1, buf, n);
			//printf("\n"); 
			fsync(1);
		}
		for (i=2; i < argc; i++) {
			send_rc(&(rc[i-2]), buf, n);
		}
	}

	for (i=2; i < argc; i++) {
		close_rc(&(rc[i-2]));
		free(rc[(i-2)].hostname);
	}
#ifndef HAVE_WINDOWS
    close(sock); 
#else
    closesocket(sock);
#endif

	return (0);
}
예제 #7
0
static void printusage(void) {
	printversion();
	printf("usage: -h         - this help\n");
	printf("       -v         - print version\n");
	printf("       -c [file]  - use config file \"file\"\n");
}
int main(int argc, char** argv) {
	/// Serial port full path to open
	char *serialport = NULL;

	/// Database file to open
	char *databasename = NULL;

	/// List of columsn to log
	char *log_columns = NULL;

	/// Number of samples to take
	int samplecount = -1;

	/// Number of samples per second
	int samplespersecond = 1;

	/// Ask to show the capabilities of the OBD device then exit
	int showcapabilities = 0;

	/// Set if the user wishes to upgrade the baudrate
	long baudrate_upgrade = -1;

	/// Time between samples, measured in microseconds
	long frametime = 0;

	/// Spam all readings to stdout
	int spam_stdout = 0;

	/// Enable elm optimisations
	int enable_optimisations = 0;

	/// Enable serial logging
	int enable_seriallog = 0;

	/// Serial log filename
	char *seriallogname = NULL;

#ifdef OBDPLATFORM_POSIX
	/// Daemonise
	int daemonise = 0;
#endif //OBDPLATFORM_POSIX

	/// Requested baudrate
	long requested_baud = -1;

	// Config File
	struct OBDGPSConfig *obd_config = obd_loadConfig(0);

	if(NULL != obd_config) {
		samplespersecond = obd_config->samplerate;
		enable_optimisations = obd_config->optimisations;
		requested_baud = obd_config->baudrate;
		baudrate_upgrade = obd_config->baudrate_upgrade;
	}

	// Do not attempt to buffer stdout at all
	setvbuf(stdout, (char *)NULL, _IONBF, 0);

	int optc;
	int mustexit = 0;
	while ((optc = getopt_long (argc, argv, shortopts, longopts, NULL)) != -1) {
		switch (optc) {
			case 'h':
				printhelp(argv[0]);
				mustexit = 1;
				break;
			case 'v':
				printversion();
				mustexit = 1;
				break;
			case 's':
				if(NULL != serialport) {
					free(serialport);
				}
				serialport = strdup(optarg);
				break;
			case 'o':
				enable_optimisations = 1;
				break;
			case 't':
				spam_stdout = 1;
				break;
			case 'u':
				{
					int newout = open(optarg, O_CREAT|O_RDWR|O_APPEND,
						S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
					if(-1 == newout) {
						perror(optarg);
					} else {
						printf("Redirecting output to %s\n", optarg);
						close(STDOUT_FILENO);
						close(STDERR_FILENO);
						dup2(newout, STDOUT_FILENO);
						dup2(newout, STDERR_FILENO);
					}
				}
				break;
#ifdef OBDPLATFORM_POSIX
			case 'm':
				daemonise = 1;
				break;
#endif //OBDPLATFORM_POSIX
			case 'c':
				samplecount = atoi(optarg);
				break;
			case 'b':
				requested_baud = strtol(optarg, (char **)NULL, 10);
				break;
			case 'B':
				baudrate_upgrade = strtol(optarg, (char **)NULL, 10);
				break;
			case 'd':
				if(NULL != databasename) {
					free(databasename);
				}
				databasename = strdup(optarg);
				break;
			case 'i':
				if(NULL != log_columns) {
					free(log_columns);
				}
				log_columns = strdup(optarg);
				break;
			case 'a':
				samplespersecond = atoi(optarg);
				break;
			case 'l':
				enable_seriallog = 1;
				if(NULL != seriallogname) {
					free(seriallogname);
				}
				seriallogname = strdup(optarg);
				break;
			case 'p':
				showcapabilities = 1;
				break;
			default:
				mustexit = 1;
				break;
		}
	}

	if(mustexit) exit(0);

	if(0 >= samplespersecond) {
		frametime = 0;
	} else {
		frametime = 1000000 / samplespersecond;
	}

	if(NULL == serialport) {
		if(NULL != obd_config && NULL != obd_config->obd_device) {
			serialport = strdup(obd_config->obd_device);
		} else {
			serialport = strdup(OBD_DEFAULT_SERIALPORT);
		}
	}
	if(NULL == databasename) {
		if(NULL != obd_config && NULL != obd_config->log_file) {
			databasename = strdup(obd_config->log_file);
		} else {
			databasename = strdup(OBD_DEFAULT_DATABASE);
		}
	}
	if(NULL == log_columns) {
		if(NULL != obd_config && NULL != obd_config->log_columns) {
			log_columns = strdup(obd_config->log_columns);
		} else {
			log_columns = strdup(OBD_DEFAULT_COLUMNS);
		}
	}


	if(enable_seriallog && NULL != seriallogname) {
		startseriallog(seriallogname);
	}


	// Open the serial port.
	int obd_serial_port = openserial(serialport, requested_baud, baudrate_upgrade);

	if(-1 == obd_serial_port) {
		fprintf(stderr, "Couldn't open obd serial port. Attempting to continue.\n");
	} else {
		fprintf(stderr, "Successfully connected to serial port. Will log obd data\n");
	}

	// Just figure out our car's OBD port capabilities and print them
	if(showcapabilities) {
		printobdcapabilities(obd_serial_port);
		
		printf("\n");

/*
		unsigned int retvals[50];
		int vals_returned;
		getobderrorcodes(obd_serial_port,
        		retvals, sizeof(retvals)/sizeof(retvals[0]), &vals_returned);

		int q = 0;
		int c = retvals[0];
		for(q=1;q<1+2*c && q+1<vals_returned;q+=2) {
			printf("Error: %s\n", obderrconvert(retvals[q], retvals[q+1]));
		}

*/

		closeserial(obd_serial_port);
		exit(0);
	}


#ifdef HAVE_GPSD
	// Open the gps device
	struct gps_data_t *gpsdata;
	gpsdata = opengps(GPSD_ADDR, GPSD_PORT);

	if(NULL == gpsdata) {
		fprintf(stderr, "Couldn't open gps port on startup.\n");
	} else {
		fprintf(stderr, "Successfully connected to gpsd. Will log gps data\n");
	}

#endif //HAVE_GPSD

	if(-1 == obd_serial_port
#ifdef HAVE_GPSD
		&& NULL == gpsdata
#endif //HAVE_GPSD
	) {
		fprintf(stderr, "Couldn't find either gps or obd to log. Exiting.\n");
		exit(1);
	}

#ifdef HAVE_DBUS
	obdinitialisedbus();
#endif //HAVE_DBUS

	// sqlite database
	sqlite3 *db;

	// sqlite statement
	sqlite3_stmt *obdinsert;

	// number of columns in the insert
	int obdnumcols;

	// sqlite return status
	int rc;

	// Open the database and create the obd table
	if(NULL == (db = opendb(databasename))) {
		closeserial(obd_serial_port);
		exit(1);
	}

	// Disable sqlite's synchronous pragma.
	/* char *zErrMsg;
	rc = sqlite3_exec(db, "PRAGMA synchronous=OFF",
					NULL, NULL, &zErrMsg);
	if(rc != SQLITE_OK) {
		printf("SQLite error %i: %s\n", rc, zErrMsg);
		sqlite3_free(zErrMsg);
	} */

	// Wishlist of commands from config file
	struct obdservicecmd **wishlist_cmds = NULL;
	obd_configCmds(log_columns, &wishlist_cmds);

	void *obdcaps = getobdcapabilities(obd_serial_port,wishlist_cmds);

	obd_freeConfigCmds(wishlist_cmds);
	wishlist_cmds=NULL;

	createobdtable(db,obdcaps);

	// Create the insert statement. On success, we'll have the number of columns
	if(0 == (obdnumcols = createobdinsertstmt(db,&obdinsert, obdcaps)) || NULL == obdinsert) {
		closedb(db);
		closeserial(obd_serial_port);
		exit(1);
	}

	createtriptable(db);

	createecutable(db);

	// All of these have obdnumcols-1 since the last column is time
	int cmdlist[obdnumcols-1]; // Commands to send [index into obdcmds_mode1]

	int i,j;
	for(i=0,j=0; i<sizeof(obdcmds_mode1)/sizeof(obdcmds_mode1[0]); i++) {
		if(NULL != obdcmds_mode1[i].db_column) {
			if(isobdcapabilitysupported(obdcaps,i)) {
				cmdlist[j] = i;
				j++;
			}
		}
	}

	freeobdcapabilities(obdcaps);
	// We create the gps table even if gps is disabled, so that other
	//  SQL commands expecting the table to at least exist will work.

	// sqlite statement
	sqlite3_stmt *gpsinsert;

	// number of columns in the insert
	int gpsnumcols;

	creategpstable(db);

	if(0 == (gpsnumcols = creategpsinsertstmt(db, &gpsinsert) || NULL == gpsinsert)) {
		closedb(db);
		closeserial(obd_serial_port);
		exit(1);
	}

#ifdef OBDPLATFORM_POSIX
	if(daemonise) {
		if(0 != obddaemonise()) {
			fprintf(stderr,"Couldn't daemonise, exiting\n");
			closeserial(obd_serial_port);
			exit(1);
		}
	}
#endif //OBDPLATFORM_POSIX

#ifdef HAVE_GPSD
	// Ping a message to stdout the first time we get
	//   enough of a satellite lock to begin logging
	int have_gps_lock = 0;
#endif //HAVE_GPSD


	install_signalhandlers();


	// The current thing returned by starttrip
	sqlite3_int64 currenttrip = 0;

	// Set when we're actually inside a trip
	int ontrip = 0;

	// The current time we're inserting
	double time_insert;

	// The last time we tried to check the gps daemon
	double time_lastgpscheck = 0;

	// Number of samples per transaction
	const int basetransactioncount = TRANSACTIONTIME * (0==samplespersecond?10:samplespersecond);

	// Store a few seconds worth of samples per transaction
	int transactioncount = 0;

	obdbegintransaction(db);

	while(samplecount == -1 || samplecount-- > 0) {

		struct timeval starttime; // start time through loop
		struct timeval endtime; // end time through loop
		struct timeval selecttime; // =endtime-starttime [for select()]

		if(0 != gettimeofday(&starttime,NULL)) {
			perror("Couldn't gettimeofday");
			break;
		}

#ifdef HAVE_DBUS
		enum obd_dbus_message msg_ret;
		while(OBD_DBUS_NOMESSAGE != (msg_ret = obdhandledbusmessages())) {
			switch(msg_ret) {
				case OBD_DBUS_STARTTRIP:
					if(!ontrip) {
						currenttrip = starttrip(db, time_insert);
						fprintf(stderr,"Created a new trip (%i)\n", (int)currenttrip);
						ontrip = 1;
					}
					break;
				case OBD_DBUS_NOMESSAGE:
				default:
					break;
			}
		}
#endif //HAVE_DBUS

		time_insert = (double)starttime.tv_sec+(double)starttime.tv_usec/1000000.0f;

		if(sig_starttrip) {
			if(ontrip) {
				fprintf(stderr,"Ending current trip\n");
				updatetrip(db, currenttrip, time_insert);
				ontrip = 0;
			}
			currenttrip = starttrip(db, time_insert);
			fprintf(stderr,"Created a new trip (%i)\n", (int)currenttrip);
			ontrip = 1;
			sig_starttrip = 0;
		}

		enum obd_serial_status obdstatus;
		if(-1 < obd_serial_port) {

			// Get all the OBD data
			for(i=0; i<obdnumcols-1; i++) {
				float val;
				unsigned int cmdid = obdcmds_mode1[cmdlist[i]].cmdid;
				int numbytes = enable_optimisations?obdcmds_mode1[cmdlist[i]].bytes_returned:0;
				OBDConvFunc conv = obdcmds_mode1[cmdlist[i]].conv;

				obdstatus = getobdvalue(obd_serial_port, cmdid, &val, numbytes, conv);
				if(OBD_SUCCESS == obdstatus) {
#ifdef HAVE_DBUS
					obddbussignalpid(&obdcmds_mode1[cmdlist[i]], val);
#endif //HAVE_DBUS
					if(spam_stdout) {
						printf("%s=%f\n", obdcmds_mode1[cmdlist[i]].db_column, val);
					}
					sqlite3_bind_double(obdinsert, i+1, (double)val);
					// printf("cmd: %02X, val: %f\n",obdcmds_mode1[cmdlist[i]].cmdid,val);
				} else {
					break;
				}
			}

			if(obdstatus == OBD_SUCCESS) {
				// If they're not on a trip but the engine is going, start a trip
				if(0 == ontrip) {
					printf("Creating a new trip\n");
					currenttrip = starttrip(db, time_insert);
					ontrip = 1;
				}
				sqlite3_bind_double(obdinsert, i+1, time_insert);
				sqlite3_bind_int64(obdinsert, i+2, currenttrip);

				// Do the OBD insert
				rc = sqlite3_step(obdinsert);
				if(SQLITE_DONE != rc) {
					printf("sqlite3 obd insert failed(%i): %s\n", rc, sqlite3_errmsg(db));
				}
			} else if(OBD_ERROR == obdstatus) {
				fprintf(stderr, "Received OBD_ERROR from serial read. Exiting\n");
				receive_exitsignal = 1;
			} else {
				// If they're on a trip, and the engine has desisted, stop the trip
				if(ontrip) {
					printf("Ending current trip\n");
					updatetrip(db, currenttrip, time_insert);
					ontrip = 0;
				}
			}
			sqlite3_reset(obdinsert);
		}

		// Constantly update the trip
		updatetrip(db, currenttrip, time_insert);

#ifdef HAVE_GPSD
		// Get the GPS data
		double lat,lon,alt,speed,course,gpstime;

		int gpsstatus = -1;
		if(NULL != gpsdata) {
			gpsstatus = getgpsposition(gpsdata, &lat, &lon, &alt, &speed, &course, &gpstime);
		} else {
			if(time_insert - time_lastgpscheck > 10) { // Try again once in a while
				gpsdata = opengps(GPSD_ADDR, GPSD_PORT);
				if(NULL != gpsdata) {
					printf("Delayed connection to gps achieved\n");
				} else {
					// fprintf(stderr, "Delayed connection to gps failed\n");
				}
				time_lastgpscheck = time_insert;
			}
		}
		if(gpsstatus < 0 || NULL == gpsdata) {
			// Nothing yet
		} else if(gpsstatus >= 0) {
			if(0 == have_gps_lock) {
				fprintf(stderr,"GPS acquisition complete\n");
				have_gps_lock = 1;
			}

			sqlite3_bind_double(gpsinsert, 1, lat);
			sqlite3_bind_double(gpsinsert, 2, lon);
			if(gpsstatus >= 1) {
				sqlite3_bind_double(gpsinsert, 3, alt);
			} else {
				sqlite3_bind_null(gpsinsert, 3);
			}
			sqlite3_bind_double(gpsinsert, 4, speed);
			sqlite3_bind_double(gpsinsert, 5, course);
			sqlite3_bind_double(gpsinsert, 6, gpstime);

			if(spam_stdout) {
				printf("gpspos=%f,%f,%f,%f,%f\n",
					lat, lon, (gpsstatus>=1?alt:-1000.0), speed, course);
			}

			// Use time worked out before.
			//  This makes table joins reliable, but the time itself may be wrong depending on gpsd lagginess
			sqlite3_bind_double(gpsinsert, 7, time_insert);

			sqlite3_bind_int64(gpsinsert, 8, currenttrip);

			// Do the GPS insert
			rc = sqlite3_step(gpsinsert);
			if(SQLITE_DONE != rc) {
				printf("sqlite3 gps insert failed(%i): %s\n", rc, sqlite3_errmsg(db));
			}
			sqlite3_reset(gpsinsert);
		}
#endif //HAVE_GPSD

		if(0 != gettimeofday(&endtime,NULL)) {
			perror("Couldn't gettimeofday");
			break;
		}

		// Set via the signal handler
		if(receive_exitsignal) {
			break;
		}


		// Commit this if we've done more than a certain number
		transactioncount++;
		transactioncount%=basetransactioncount;
		if(0 == transactioncount) {
			obdcommittransaction(db);
			obdbegintransaction(db);
		}

		
		// usleep() not as portable as select()

		if(0 < frametime) {
			selecttime.tv_sec = endtime.tv_sec - starttime.tv_sec;
			if (selecttime.tv_sec != 0) {
					endtime.tv_usec += 1000000*selecttime.tv_sec;
					selecttime.tv_sec = 0;
			}
			selecttime.tv_usec = (frametime) - 
					(endtime.tv_usec - starttime.tv_usec);
			if(selecttime.tv_usec < 0) {
					selecttime.tv_usec = 1;
			}
			select(0,NULL,NULL,NULL,&selecttime);
		}
	}

	obdcommittransaction(db);

	if(0 != ontrip) {
		updatetrip(db, currenttrip, time_insert);
		ontrip = 0;
	}

	sqlite3_finalize(obdinsert);
	sqlite3_finalize(gpsinsert);

	closeserial(obd_serial_port);
#ifdef HAVE_GPSD
	if(NULL != gpsdata) {
		gps_close(gpsdata);
	}
#endif //HAVE_GPSD
	closedb(db);

	if(enable_seriallog) {
		closeseriallog();
	}

	if(NULL != log_columns) free(log_columns);
	if(NULL != databasename) free(databasename);
	if(NULL != serialport) free(serialport);

	obd_freeConfig(obd_config);
	return 0;
}
예제 #9
0
int main(int argc,char* argv[]) {
    memset(&config, 0, sizeof(config));
    // Register signal and signal handler
    signal(SIGINT, signal_shutdown);    
    char directory[MAXPATHLEN];
    strcpy(config.soundCardName,"HPSDR");
    strcpy(config.server_address,"127.0.0.1"); // localhost
    strcpy(config.share_config_file, getenv("HOME"));
    strcat(config.share_config_file, "/dspserver.conf");
    processCommands(argc,argv,&config);

#ifdef THREAD_DEBUG
    sdr_threads_init();
#endif /* THREAD_DEBUG */

    fprintf(stderr, "Reading conf file %s\n", config.share_config_file);
    init_register(config.share_config_file); // we now read our conf always
	 // start web registration if set
    if  (toShareOrNotToShare) {
        fprintf(stderr, "Activating Web register\n");
    }
    fprintf(stderr,"gHPSDR rx %d (Version %s)\n",receiver,VERSION);
    printversion();
    setSoundcard(getSoundcardId(config.soundCardName));

    // initialize DttSP
    if(getcwd(directory, sizeof(directory))==NULL) {
        fprintf(stderr,"current working directory path is > MAXPATHLEN");
        exit(1);
    }
    Setup_SDR(directory);
    Release_Update();
    SetTRX(0,0); // thread 0 is for receive
    SetTRX(1,1);  // thread 1 is for transmit
    SetRingBufferOffset(0,config.offset);
    SetThreadProcessingMode(0,RUN_PLAY);
    SetThreadProcessingMode(1,RUN_PLAY);
    SetSubRXSt(0,1,1);
    SetRXOutputGain(0,0,0.20);
    SetRXOsc(0,0, -LO_offset);
    SetRXOsc(0,1, -LO_offset);
    reset_for_buflen(0,1024);
    reset_for_buflen(1,1024);

    client_init(receiver);        // create the main thread responsible for listen TCP socket
                                  // on the read callback:
                                  //    accept and interpret the commands from remote GUI  
                                  //    parse mic data from remote and enque them into Mic_audio_stream queue
                                  //    see client.c
                                  //
                                  // on the write callback:
                                  //    read the audio_stream_queue and send into the TCP socket
                                  //
    audio_stream_init(receiver);
    audio_stream_reset();

    codec2 = codec2_create(CODEC2_MODE_3200);
    G711A_init();
    ozy_init(config.server_address);   // create and starts iq_thread in ozy.c in order to
                                       // receive iq stream from hardware server
                                       // process it in DttSP
                                       // makes the sample rate adaption for resulting audio
                                       // puts audio stream in a queue (via calls to audio_stream_queue_add 
                                       // in audio_stream_put_samples() in audiostream.c)
                                       //
                                       // in case of HPSDR hardware (that is provided with a local D/A converter
                                       // sends via ozy_send() the audio back to the hardware server
    SetMode(1, 0, USB);
    SetTXFilter(1, 150, 2850);
    SetTXOsc(1, LO_offset);
    SetTXAMCarrierLevel(1, 0.5);

    tx_init();	// create and starts the tx_thread (see client.c)
                // the tx_thread reads the Mic_audio_stream queue, makes the sample rate adaption
                // process the data into DttSP in order to get the modulation process done,
                // and sends back to the hardware server process (via ozy_send() )

#ifdef THREAD_DEBUG
    /* Note that some thread interactions will be lost at startup due to
     * the fact that the subsystem threads are all started.  We can't
     * init this until late, though, or we'll catch initializations
     * performed at boot time as errors. */
    if (config.thread_debug) {
        sdr_threads_debug(TRUE);
    }
#endif /* THREAD_DEBUG */

    while(1) {
        sleep(10000);
    }

 //   codec2_destroy(codec2);
    return 0;
}
예제 #10
0
파일: ntldd.c 프로젝트: Forty-Bot/ntldd
int main (int argc, char **argv)
{
  int i;
  int verbose = 0;
  int unused = 0;
  int datarelocs = 0;
  int functionrelocs = 0;
  int skip = 0;
  int files = 0;
  int recursive = 0;
  int list_exports = 0;
  int list_imports = 0;
  int files_start = -1;
  int files_count = 0;

  SearchPaths sp;
  memset(&sp, 0, sizeof (sp));
  sp.path = calloc (1, sizeof (char*));

  for (i = 1; i < argc; i++)
  {
    if (strcmp (argv[i], "--version") == 0)
      printversion ();
    else if (strcmp (argv[i], "-v") == 0 || strcmp (argv[i], "--verbose") == 0)
      verbose = 1;
    else if (strcmp (argv[i], "-u") == 0 || strcmp (argv[i], "--unused") == 0)
      unused = 1;
    else if (strcmp (argv[i], "-d") == 0 || 
        strcmp (argv[i], "--data-relocs") == 0)
      datarelocs = 1;
    else if (strcmp (argv[i], "-r") == 0 || 
        strcmp (argv[i], "--function-relocs") == 0)
      functionrelocs = 1;
    else if (strcmp (argv[i], "-R") == 0 || 
        strcmp (argv[i], "--recursive") == 0)
      recursive = 1;
    else if (strcmp (argv[i], "-e") == 0 || 
        strcmp (argv[i], "--list-exports") == 0)
      list_exports = 1;
    else if (strcmp (argv[i], "-i") == 0 || 
        strcmp (argv[i], "--list-imports") == 0)
      list_imports = 1;
    else if ((strcmp (argv[i], "-D") == 0 || strcmp (argv[i], "--search-dir") == 0) && i < argc - 1)
    {
      char* add_dirs = argv[i+1];
      if (*add_dirs == '"')
          add_dirs++;
      char* sep = strchr(add_dirs, ';');
      do {
        if (sep)
            *sep = '\0';
        sp.count++;
        sp.path = (char**)realloc(sp.path, sp.count * sizeof(char*));
        if (!sep)
        {
          char* p = strrchr(add_dirs, '"');
          if (p)
            *p = '\0';
        }
        sp.path[sp.count - 1] = strdup(add_dirs);
        add_dirs = sep + 1;
        if (!sep)
            break;
        sep = strchr(add_dirs, ';');
      } while (1);
      i++;
    }
    else if (strcmp (argv[i], "--help") == 0)
    {
      printhelp (argv[0]);
      skip = 1;
      break;
    }
    else if (strcmp (argv[i], "--") == 0)
    {
      files = 1;
    }
    else if (strlen (argv[i]) > 1 && argv[i][0] == '-' && (argv[i][1] == '-' ||
        strlen (argv[i]) == 2) && !files)
    {
      fprintf (stderr, "Unrecognized option `%s'\n\
Try `ntldd --help' for more information\n", argv[i]);
      skip = 1;
      break;
    }
    else if (files_start < 0)
예제 #11
0
파일: wmifs.c 프로젝트: d-torrance/dockapps
int main(int argc, char *argv[])
{

	int		i;

	color[0] = 0;

	/* Parse Command Line */

	for (i = 1; i < argc; i++) {
		char *arg = argv[i];

		if (*arg == '-') {
			switch (arg[1]) {
			case 'c' :
				if (argc > i+1) {
					strncpy(color, argv[i+1], sizeof(color));
					i++;
				}
				break;
			case 'd':
				if (strcmp(arg+1, "display")) {
					usage();
					exit(1);
				}
				break;
			case 'g':
				if (strcmp(arg+1, "geometry")) {
					usage();
					exit(1);
				}
				break;
			case 'i':
				active_interface = argv[i+1];
				i++;
				break;
			case 'I':
				SampleInt = atof(argv[i+1]) * 1000;
				i++;
				break;
			case 'l':
				LockMode = 1;
				break;
			case 's':
				ScrollSpeed = atof(argv[i+1]) * 1000;
				i++;
				break;
			case 'v':
				printversion();
				exit(0);
				break;
			case 'w':
				WaveForm = 1;
				break;
			default:
				if (strcmp(argv[i-1], "-geometry")) {
					usage();
					exit(0);
				}
				break;
			}
		}
	}

	wmifs_routine(argc, argv);
	return 0;
}
예제 #12
0
파일: pipic.c 프로젝트: oh7bf/PiPIC
int main(int argc, char **argv)
{  
  int verb=0; // 1=verbosed output
  int rbyte=0; // read byte
  int rword=0; // read 16-bit word
  int rword2=0; // read 32-bit word
  int rdata=0; // read data
  int wbyte=0; // write byte
  int wword=0; // write 16-bit word
  int wword2=0; // write 32-bit word
  int wdata=0; // data to write
  int rnxt=0;
  int fd;
  char fileName[100]="/dev/i2c-1";
  int  address=0x00;
  int  cmd=-1; // no operation
  unsigned char buf[10];

  int optch=0;
  while(optch!=-1)
    {
      optch=getopt(argc,argv,"a:c:d:r:hvV");
      if(optch=='a')
	{
          sscanf(optarg,"%X",&address);
	}
      if(optch=='c')
	{
          sscanf(optarg,"%X",&cmd);        
	}
      if(optch=='d')
        {
          if(optarg[strlen(optarg)-1]=='b') wbyte=1;
          if(optarg[strlen(optarg)-1]=='w') wword=1;
          if(optarg[strlen(optarg)-1]=='W') wword2=1;
          wdata=atoi(optarg);          
        }
      if(optch=='r')
	{
          if(optarg[0]=='b') rbyte=1;
          if(optarg[0]=='w') rword=1;
          if(optarg[0]=='W') rword2=1;
	}
      if(optch=='v')
	{
	  verb=1;
	}
      if(optch=='h')
	{
	  printusage();
	  return 0;
	}
      if(optch=='V')
	{
	  printversion();
	  return 0;
	}
    }

  if((address<0x03)||(address>0x77)||(cmd>255))
    {
      printusage();
      return -1;
    }

// open port for reading and writing
  if(verb==1) printf("Open %s\n", fileName);
  if((fd = open(fileName, O_RDWR)) < 0) 
  {
     perror("Failed to open i2c port");
     return -1;
  }

  if(verb==1) printf("Chip address 0x%02x\n", address);
  if(ioctl(fd, I2C_SLAVE, address) < 0) 
  {
     perror("Unable to get bus access to talk to slave");
     return -1;
  }

  if((cmd>=0)&&(cmd<=255))
  { 
     buf[0]=cmd;
     if(wbyte==1)
     { 
        buf[1]=wdata;
        if(verb==1) printf("Send 0x%02x%02x\n",buf[0],buf[1]);
        if((write(fd, buf, 2)) != 2) 
        {
           perror("Error writing to i2c slave");
           return -1;
        }
     }
     else if(wword==1)
     { 
        buf[1]=(int)(wdata/256);
        buf[2]=wdata%256;
        if(verb==1) printf("Send 0x%02x%02x%02x\n",buf[0],buf[1],buf[2]); 
        if((write(fd, buf, 3)) != 3) 
        {
           perror("Error writing to i2c slave");
           return -1;
        }
     }
     else if(wword2==1)
     { 
        buf[1]=(int)(wdata/16777216);
        rnxt=wdata%16777216;
        buf[2]=(int)(rnxt/65536);
        rnxt=rnxt%65536;
        buf[3]=(int)(rnxt/256);
        buf[4]=rnxt%256;
        if(verb==1) printf("Send 0x%02x%02x%02x%02x%02x\n",buf[0],buf[1],buf[2],buf[3],buf[4]);
        if((write(fd, buf, 5)) != 5) 
        {
           perror("Error writing to i2c slave");
           return -1;
        }
     }
     else
     {
        if(verb==1) printf("Send 0x%02x\n",buf[0]);
        if((write(fd, buf, 1)) != 1) 
        {
           perror("Error writing to i2c slave");
           return -1;
        }
     }
  }


  if(rbyte==1)
  {
     if(read(fd, buf,1)!=1) 
     {
        perror("Unable to read from slave");
        return -1;
     }
     else 
     {
        if(verb==1) printf("Receive 0x%02x\n",buf[0]);
        rdata=buf[0];
        printf ("%d\n",rdata);
     }
  } 
  else if(rword==1)
  {
     if(read(fd, buf,2)!=2) 
     {
        perror("Unable to read from slave");
        return -1;
     }
     else 
     {
        if(verb==1) printf("Receive 0x%02x%02x\n",buf[0],buf[1]); 
        rdata=256*buf[0]+buf[1];
        printf ("%d\n",rdata);
     }
  }
  else if(rword2==1)
  {
     if(read(fd, buf,4)!=4) 
     {
        perror("Unable to read from slave");
        return -1;
     }
     else 
     {
        if(verb==1) printf("Receive 0x%02x%02x%02x%02x\n",buf[0],buf[1],buf[2],buf[3]);
        rdata=16777216*buf[0]+65536*buf[1]+256*buf[2]+buf[3];
        printf ("%d\n",rdata);
     }
  }

  return 0;
}
예제 #13
0
파일: pcsensor2.c 프로젝트: nonoo/pcsensor2
int main(int argc, char **argv) {
	int r, i, usbdevcount;
	char *endptr;
	int cmdline_bus = -1, cmdline_dev = -1;
	libusb_device **usbdevlist = NULL;
	struct libusb_device_descriptor desc;
	libusb_device *probe_usbdev = NULL;
	float temp;

	while ((r = getopt(argc, argv, "vb:d:qh")) != -1) {
		switch (r) {
			case 'v':
				printversion();
				break;
			case 'b':
				errno = 0;
				cmdline_bus = strtol(optarg, &endptr, 10);
				if (*endptr != 0 || errno != 0) {
					fprintf(stderr, "invalid bus number\n");
					return 1;
				}
				break;
			case 'd':
				errno = 0;
				cmdline_dev = strtol(optarg, &endptr, 10);
				if (*endptr != 0 || errno != 0) {
					fprintf(stderr, "invalid device address\n");
					return 1;
				}
				break;
			case 'q':
				debug = 0;
				break;
			case 'h':
				printusage();
				return 0;
				break;
			default:
				if (isprint(optopt))
					fprintf(stderr, "unknown option '-%c'.\n", optopt);
				else
					fprintf(stderr, "unknown option character '-%x'.\n", optopt);
				return 1;
		}
	}

	if (optind < argc || (cmdline_dev && !cmdline_bus)) {
		printusage();
		return 1;
	}

	r = libusb_init(NULL);
	if (r < 0) {
		fprintf(stderr, "error: libusb init error\n");
		return 1;
	}

	libusb_set_debug(NULL, 3);

	if (debug)
		printf("opening device vid=%.4x pid=%.4x...\n", USB_VID, USB_PID);

	usbdevcount = libusb_get_device_list(NULL, &usbdevlist);
	for (i = 0; i < usbdevcount; i++) {
		probe_usbdev = usbdevlist[i];
		r = libusb_get_device_descriptor(probe_usbdev, &desc);
		if (r >= 0 && desc.idVendor == USB_VID && desc.idProduct == USB_PID) {
			if (cmdline_bus >= 0 && libusb_get_bus_number(probe_usbdev) != cmdline_bus)
				continue;
			if (cmdline_dev >= 0 && libusb_get_device_address(probe_usbdev) != cmdline_dev)
				continue;

			r = libusb_open(probe_usbdev, &usbdevh);
			if (r >= 0 && debug)
				printf("device opened\n");
			break;
		}
	}
	if (usbdevlist)
		libusb_free_device_list(usbdevlist, 1);
	if (!usbdevh) {
		fprintf(stderr, "error: can't find device\n");
		libusb_exit(NULL);
		return 1;
	}

    if (libusb_kernel_driver_active(usbdevh, 0))
		libusb_detach_kernel_driver(usbdevh, 0);
    if (libusb_kernel_driver_active(usbdevh, 1))
		libusb_detach_kernel_driver(usbdevh, 1);

	r = libusb_set_configuration(usbdevh, 1);
	if (r < 0) {
		fprintf(stderr, "error: can't set usb configuration\n");
		return 1;
	}

	r = libusb_claim_interface(usbdevh, 0);
	if (r < 0) {
		fprintf(stderr, "error: can't claim interface 0\n");
		libusb_close(usbdevh);
		libusb_exit(NULL);
		return 1;
	}
	r = libusb_claim_interface(usbdevh, 1);
	if (r < 0) {
		fprintf(stderr, "error: can't claim interface 1\n");
		libusb_release_interface(usbdevh, 0);
		libusb_close(usbdevh);
		libusb_exit(NULL);
		return 1;
	}
	if (debug)
		printf("device claimed\n");

	r = readtemp(&temp);
	if (r >= 0) {
		if (debug)
			printf("temperature: %f°C\n", temp);
		else
			printf("%f\n", temp);
	}

	libusb_release_interface(usbdevh, 0);
	libusb_release_interface(usbdevh, 1);
	libusb_close(usbdevh);
	libusb_exit(NULL);

	return 0;
}
예제 #14
0
파일: handlers.c 프로젝트: rumbleh/scanmem
bool handler__help(globals_t * vars, char **argv, unsigned argc)
{
    bool ret = false;
    list_t *commands = vars->commands;
    element_t *np = NULL;
    command_t *def = NULL;
    assert(commands != NULL);
    assert(argc >= 1);

    np = commands->head;

    /* pager support, dirty ugly hardcoded */
    FILE *outfd = popen("more", "w"); 
    if (outfd == NULL)
    {
        show_warn("Cannot execute pager, fall back to normal output\n");
        outfd = stderr;
    }

    /* print version information for generic help */
    if (argv[1] == NULL)
        printversion(outfd);

    /* traverse the commands list, printing out the relevant documentation */
    while (np) {
        command_t *command = np->data;

        /* remember the default command */
        if (command->command == NULL)
            def = command;

        /* just `help` with no argument */
        if (argv[1] == NULL) {
            /* NULL shortdoc means dont print in help listing */
            if (command->shortdoc == NULL) {
                np = np->next;
                continue;
            }

            /* print out command name */
            fprintf(outfd, "%-*s%s\n", DOC_COLUMN, command->command ? command->command : "default", command->shortdoc);

            /* detailed information requested about specific command */
        } else if (command->command
                   && strcasecmp(argv[1], command->command) == 0) {
            fprintf(outfd, "%s\n", command->longdoc ? command-> longdoc : "missing documentation");
            ret = true;
            goto retl;
        }

        np = np->next;
    }

    if (argc > 1) {
        show_error("unknown command `%s`\n", argv[1]);
        ret = false;
    } else if (def) {
        fprintf(outfd, "\n%s\n", def->longdoc ? def->longdoc : "");
        ret = true;
    }
    
    ret = true;

retl:
    if (outfd != stderr)
        pclose(outfd);

    return ret;
}