Пример #1
0
std::string CNetworkInterfaceLinux::GetCurrentDefaultGateway(void)
{
   std::string result;

#if defined(TARGET_DARWIN)
  FILE* pipe = popen("echo \"show State:/Network/Global/IPv4\" | scutil | grep Router", "r");
  Sleep(100);
  if (pipe)
  {
    std::string tmpStr;
    char buffer[256] = {'\0'};
    if (fread(buffer, sizeof(char), sizeof(buffer), pipe) > 0 && !ferror(pipe))
    {
      tmpStr = buffer;
      if (tmpStr.length() >= 11)
        result = tmpStr.substr(11);
    }
    pclose(pipe);
  }
  if (result.empty())
    CLog::Log(LOGWARNING, "Unable to determine gateway");
#elif defined(TARGET_FREEBSD)
   size_t needed;
   int mib[6];
   char *buf, *next, *lim;
   char line[16];
   struct rt_msghdr *rtm;
   struct sockaddr *sa;
   struct sockaddr_in *sockin;

   mib[0] = CTL_NET;
   mib[1] = PF_ROUTE;
   mib[2] = 0;
   mib[3] = 0;
   mib[4] = NET_RT_DUMP;
   mib[5] = 0;
   if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
      return result;

   if ((buf = (char *)malloc(needed)) == NULL)
      return result;

   if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
      free(buf);
      return result;
   }

   lim  = buf + needed;
   for (next = buf; next < lim; next += rtm->rtm_msglen) {
      rtm = (struct rt_msghdr *)next;
      sa = (struct sockaddr *)(rtm + 1);
      sa = (struct sockaddr *)(SA_SIZE(sa) + (char *)sa);	
      sockin = (struct sockaddr_in *)sa;
      if (inet_ntop(AF_INET, &sockin->sin_addr.s_addr,
         line, sizeof(line)) == NULL) {
            free(buf);
            return result;
	  }
	  result = line;
      break;
   }
   free(buf);
#else
   FILE* fp = fopen("/proc/net/route", "r");
   if (!fp)
   {
     // TBD: Error
     return result;
   }

   char* line = NULL;
   char iface[16];
   char dst[128];
   char gateway[128];
   size_t linel = 0;
   int n;
   int linenum = 0;
   while (getdelim(&line, &linel, '\n', fp) > 0)
   {
      // skip first two lines
      if (linenum++ < 1)
         continue;

      // search where the word begins
      n = sscanf(line,  "%16s %128s %128s",
         iface, dst, gateway);

      if (n < 3)
         continue;

      if (strcmp(iface, m_interfaceName.c_str()) == 0 &&
          strcmp(dst, "00000000") == 0 &&
          strcmp(gateway, "00000000") != 0)
      {
         unsigned char gatewayAddr[4];
         int len = CNetwork::ParseHex(gateway, gatewayAddr);
         if (len == 4)
         {
            struct in_addr in;
            in.s_addr = (gatewayAddr[0] << 24) | (gatewayAddr[1] << 16) |
                        (gatewayAddr[2] << 8) | (gatewayAddr[3]);
            result = inet_ntoa(in);
            break;
         }
      }
   }
   free(line);
   fclose(fp);
#endif

   return result;
}
Пример #2
0
void *computervision_thread_main(void* data)
{
  // Video Input
  struct vid_struct vid;
  vid.device = (char*)"/dev/video1";
  vid.w=1280;
  vid.h=720;
  vid.n_buffers = 4;
  if (video_init(&vid)<0) {
    printf("Error initialising video\n");
    computervision_thread_status = -1;
    return 0;
  }

  // Frame Grabbing
  struct img_struct* img_new = video_create_image(&vid);

  // Frame Resizing
  uint8_t quality_factor = IMAGE_QUALITY_FACTOR;
  uint8_t dri_jpeg_header = 1;

  struct img_struct small;
  small.w = vid.w / IMAGE_DOWNSIZE_FACTOR;
  small.h = vid.h / IMAGE_DOWNSIZE_FACTOR;
  small.buf = (uint8_t*)malloc(small.w*small.h*2);

  // Commpressed image buffer
  uint8_t* jpegbuf = (uint8_t*)malloc(vid.h*vid.w*2);

  // file index (search from 0)
  int file_index = 0;

  int microsleep = (int)(1000000. / IMAGE_FPS);

  while (computer_vision_thread_command > 0)
  {
    usleep(microsleep);
    video_grab_image(&vid, img_new);

    // Resize
    resize_uyuv(img_new, &small, IMAGE_DOWNSIZE_FACTOR);

    // JPEG encode the image:
    uint32_t image_format = FOUR_TWO_TWO;  // format (in jpeg.h)
    uint8_t* end = encode_image (small.buf, jpegbuf, quality_factor, image_format, small.w, small.h, dri_jpeg_header);
    uint32_t size = end-(jpegbuf);

#if IMAGE_SAVE
    FILE* save;
    char save_name[128];
    if (system("mkdir -p /data/video/images") == 0) {
      // search available index (max is 99)
      for ( ; file_index < 99; file_index++) {
        printf("search %d\n",file_index);
        sprintf(save_name,"/data/video/images/img_%02d.jpg",file_index);
        // test if file exists or not
        if (access(save_name, F_OK) == -1) {
          printf("access\n");
          save = fopen(save_name, "w");
          if (save != NULL) {
            fwrite(jpegbuf, sizeof(uint8_t), size, save);
            fclose(save);
          }
          else {
            printf("Error when opening file %s\n", save_name);
          }
          // leave for loop
          break;
        }
        else {printf("file exists\n");}
      }
    }
#endif

    // Fork process
    int status;
    pid_t pid = fork();

    if (pid == 0) {
      // Open process to send using netcat in child process
      char nc_cmd[64];
      sprintf(nc_cmd, "nc %s %d", IMAGE_SERVER_IP, IMAGE_SERVER_PORT);
      FILE* netcat;
      netcat = popen(nc_cmd, "w");
      if (netcat != NULL) {
        fwrite(jpegbuf, sizeof(uint8_t), size, netcat);
        if (pclose(netcat) == 0) {
          printf("Sending image succesfully\n");
        }
      }
      else {
        printf("Fail sending image\n");
      }
      exit(0);
    }
    else if (pid < 0) {
      printf("Fork failed\n");
    }
    else {
      // Parent is waiting for child to terminate
      wait(&status);
    }

  }
  printf("Thread Closed\n");
  video_close(&vid);
  computervision_thread_status = -100;
  return 0;
}
Пример #3
0
int FPutFile(TRUSERID *handle,int iRequest,ST_PACK *rPack,int *pRetCode,char *szMsg)
{
	//ST_SDPACK *psd;
	int ret;
	char szCmd[256] = "";
	char filepath[256]="";
	char sFileName[256]={0};
	char chkdate[9] = "";
	FILE *fp;
	struct stat fst;
	memset(&fst,0,sizeof fst);

	printf("filetransfer:主动获取对账文件标志[%d]\n", rPack->lvol2);
	
	if(rPack->lvol2==1)			// 需主动获取对账文件
	{
		ret = Bank_Checkacc(handle,rPack,pRetCode,szMsg);
		if(ret)
		{
			sprintf(szMsg, "FPutFile:下载对账文件请求失败,错误代码[%d]", ret);
			printf(szMsg);
			return -1;
		}

		printf("FPutFile:下载对账文件请求成功\n");
	}
	
	/* 重命名文件
	将银行chkdate 那天的对账文件,改名为 sFileName
	*/
	sprintf(szCmd,"getbankchkfile.sh %s",rPack->vsmess);

	printf("FPutFile:szCmd[%s]\n", szCmd);

	if((fp = popen(szCmd, "r"))==NULL)
	{
		sprintf(szMsg, "exec cmd[%s] error",szCmd);
		return -1;
	}
	char line[1024]={0};
	char lastline[1024]={0};
	while(!feof(fp))
	{
		memset(line,0,sizeof(line));
		if(fgets(line, sizeof(line),fp)==NULL)
		{
			if(feof(fp))
				break;
			else
			{
				pclose(fp);
				return -1;
			}
		}
		strcpy(lastline,line);
		if(strstr(line,"filename:")!=0)
		{
			strcpy(sFileName,line+strlen("filename:"));
			break;
		}		
	}
	pclose(fp);

	printf("FPutFile:sFileName[%s]\n", sFileName);
	
	if(strlen(sFileName)<1)
	{
		printf("FPutFile:%s\n", lastline);
		strcpy(szMsg,lastline);
		return -1;
	}
	
	trim(sFileName);
	printf("downfile:[%s]\n",sFileName);
	stat(sFileName, &fst);
	printf("filelen:%d\n", fst.st_size);
	int maxlen = sizeof(ST_PACK) - 4;
	if (maxlen > 4000)
		maxlen = 4000;
	fp = fopen(sFileName, "rb");
	if (fp == NULL)
	{
		sprintf(szMsg, "Cannot open the file:<%s>!", sFileName);
		return  9999;
	}
	ST_SDPACK *psd=(ST_SDPACK *)rPack;
	if(fst.st_size>0)
	{
		while (!feof(fp))
		{	
			psd->usDataLength = fread(psd->data, 1, maxlen, fp);
			PutRowData(rPack);
		}
	}
	fclose(fp);		

	ST_CPACK aPack;
	ST_PACK *outPack = &(aPack.pack);
	ResetNormalCPack(&aPack,0,1);
	SetCol(handle,0);
	SetCol(handle,F_LVOL0,F_VSVARSTR0,F_VSMESS, 0);
	outPack->lvol0 = fst.st_size;
	strcpy(outPack->vsvarstr0, sFileName);
	strcpy(outPack->vsmess, szMsg);
	PutRow(handle, outPack, pRetCode, szMsg);
	return 0;
}
Пример #4
0
// Fetch the X library directory, using xmkmf(1)
static const _XtString xlibdir(Display *display, bool verbose = false)
{
    static bool tried = false;
    static const _XtString dir = 0;

    if (tried)
	return dir;
    tried = true;

    if (!is_cmd_file(cmd_file("xmkmf")))
	return dir;		// No `xmkmf' in PATH
    if (!is_cmd_file(cmd_file("make")))
	return dir;		// No `make' in PATH

    static const char *shell_command =
	""
#include "xlibdir.C"
	"";

    String me, my_class;
    XtGetApplicationNameAndClass(display, &me, &my_class);

    if (verbose)
    {
	std::cout << "Checking for X11 library directory... ";
	std::cout.flush();
    }

    const string s1 = "/bin/sh -c " + sh_quote(shell_command); 
    FILE *fp = popen(s1.chars(), "r");
    if (fp == 0)
    {
	if (verbose)
	{
	    std::cout << strerror(errno) << "\n";
	    std::cout.flush();
	}
	return dir;
    }

    char buffer[PATH_MAX];
    buffer[0] = '\0';
    fgets(buffer, sizeof(buffer), fp);
    pclose(fp);

    int len = strlen(buffer);
    if (len > 0 && buffer[len - 1] == '\n')
	buffer[len - 1] = '\0';

    if (buffer[0] == '/')	// Sanity check
	dir = (String)XtNewString(buffer);

    if (verbose)
    {
	if (dir)
	    std::cout << dir << "\n";
	else
	    std::cout << "(not found)\n";
	std::cout.flush();
    }

    return dir;
}
Пример #5
0
bool generate_sql_makefile()
{
    if (new_sql_updates.empty()) return true;

    // find all files in the update dir
    snprintf(cmd, MAX_CMD, "git show HEAD:%s", sql_update_dir);
    if ((cmd_pipe = popen(cmd, "r")) == NULL)
        return false;

    // skip first two lines
    if (!fgets(buffer, MAX_BUF, cmd_pipe)) { pclose(cmd_pipe); return false; }
    if (!fgets(buffer, MAX_BUF, cmd_pipe)) { pclose(cmd_pipe); return false; }

    char newname[MAX_PATH];
    std::set<std::string> file_list;
    sql_update_info info;

    while (fgets(buffer, MAX_BUF, cmd_pipe))
    {
        buffer[strlen(buffer) - 1] = '\0';
        if (buffer[strlen(buffer) - 1] != '/' &&
                strncmp(buffer, "Makefile.am", MAX_BUF) != 0)
        {
            if (new_sql_updates.find(buffer) != new_sql_updates.end())
            {
                if (!get_sql_update_info(buffer, info)) return false;
                snprintf(newname, MAX_PATH, REV_PRINT "_%s_%0*d_%s%s%s.sql", rev, info.parentRev, 2, info.nr, info.db, info.has_table ? "_" : "", info.table);
                file_list.insert(newname);
            }
            else
                file_list.insert(buffer);
        }
    }

    pclose(cmd_pipe);

    // write the makefile
    char file_name[MAX_PATH];
    snprintf(file_name, MAX_PATH, "%s%s/Makefile.am", path_prefix, sql_update_dir);
    FILE* fout = fopen(file_name, "w");
    if (!fout) { pclose(cmd_pipe); return false; }

    fprintf(fout,
            "# This code is part of MaNGOS. Contributor & Copyright details are in AUTHORS/THANKS.\n"
            "#\n"
            "# This program is free software; you can redistribute it and/or modify\n"
            "# it under the terms of the GNU General Public License as published by\n"
            "# the Free Software Foundation; either version 2 of the License, or\n"
            "# (at your option) any later version.\n"
            "#\n"
            "# This program is distributed in the hope that it will be useful,\n"
            "# but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
            "# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
            "# GNU General Public License for more details.\n"
            "#\n"
            "# You should have received a copy of the GNU General Public License\n"
            "# along with this program; if not, write to the Free Software\n"
            "# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\n"
            "\n"
            "## Process this file with automake to produce Makefile.in\n"
            "\n"
            "## Sub-directories to parse\n"
            "SUBDIRS = before_upgrade_to_0.13\n"
            "\n"
            "## Change installation location\n"
            "#  datadir = mangos/%s\n"
            "pkgdatadir = $(datadir)/mangos/%s\n"
            "\n"
            "## Files to be installed\n"
            "#  Install basic SQL files to datadir\n"
            "pkgdata_DATA = \\\n",
            sql_update_dir, sql_update_dir
    );

    for(std::set<std::string>::iterator itr = file_list.begin(), next; itr != file_list.end(); ++itr)
    {
        next = itr; ++next;
        fprintf(fout, "\t%s%s\n", itr->c_str(), next == file_list.end() ? "" : " \\");
    }

    fprintf(fout,
            "\n## Additional files to include when running 'make dist'\n"
            "#  SQL update files, to upgrade database schema from older revisions\n"
            "EXTRA_DIST = \\\n"
           );

    for (std::set<std::string>::iterator itr = file_list.begin(), next; itr != file_list.end(); ++itr)
    {
        next = itr; ++next;
        fprintf(fout, "\t%s%s\n", itr->c_str(), next == file_list.end() ? "" : " \\");
    }

    fclose(fout);

    snprintf(cmd, MAX_CMD, "git add %s%s/Makefile.am", path_prefix, sql_update_dir);
    system_switch_index(cmd);

    return true;
}
struct chipInfo_t *getChipInfo(const char *filename, int *num, uint32_t msmversion)
{

    const char str1[] = "dtc -I dtb -O dts \"";
    const char str2[] = "\" 2>&1";
    char *buf, *pos;
    char *line = NULL;
    size_t line_size;
    FILE *pfile;
    int llen;
    struct chipInfo_t *chip = NULL, *tmp;
    uint32_t data[3] = {0, 0, 0};
    uint32_t data_st[2] = {0, 0};
    char *tok, *sptr = NULL;
    int i, entryValid, entryEnded;
    int count = 0, count1 = 0, count2 =0;
    int entryValidST, entryEndedST, entryValidDT, entryEndedDT;
    struct chipId_t *chipId = NULL, *cId = NULL, *tmp_id = NULL;
    struct chipSt_t *chipSt = NULL, *cSt = NULL, *tmp_st = NULL;

    line_size = 1024;
    line = (char *)malloc(line_size);
    if (!line) {
        log_err("Out of memory\n");
        return NULL;
    }

    llen = sizeof(char) * (strlen(dtc_path) +
                           strlen(str1) +
                           strlen(str2) +
                           strlen(filename) + 1);
    buf = (char *)malloc(llen);
    if (!buf) {
        log_err("Out of memory\n");
        free(line);
        return NULL;
    }

    strncpy(buf, dtc_path, llen);
    strncat(buf, str1, llen);
    strncat(buf, filename, llen);
    strncat(buf, str2, llen);

    pfile = popen(buf, "r");
    free(buf);

    if (pfile == NULL) {
        log_err("... skip, fail to decompile dtb\n");
    } else {
        /* Find "qcom,msm-id" */
        while ((llen = getline(&line, &line_size, pfile)) != -1) {
            if (msmversion == 1) {
                if ((pos = strstr(line, dt_tag)) != NULL) {
                    pos += strlen(dt_tag);

                    entryEnded = 0;
                    while (1) {
                        entryValid = 1;
                        for (i = 0; i < 3; i++) {
                            tok = strtok_r(pos, " \t", &sptr);
                            pos = NULL;
                            if (tok != NULL) {
                                if (*tok == '>') {
                                    entryEnded = 1;
                                    entryValid = 0;
                                    break;
                                }
                                data[i] = strtoul(tok, NULL, 0);
                            } else {
                                data[i] = 0;
                                entryValid = 0;
                                entryEnded = 1;
                            }
                        }
                        if (entryEnded) {
                            free(line);
                            pclose(pfile);
                            *num = count;
                            return chip;
                        }
                        if (entryValid) {
                            tmp = (struct chipInfo_t *)
                                      malloc(sizeof(struct chipInfo_t));
                            if (!tmp) {
                                log_err("Out of memory\n");
                                break;
                            }
                            if (!chip) {
                                chip = tmp;
                                chip->t_next = NULL;
                            } else {
                                tmp->t_next = chip->t_next;
                                chip->t_next = tmp;
                            }
                            tmp->chipset  = data[0];
                            tmp->platform = data[1];
                            tmp->subtype  = 0;
                            tmp->revNum   = data[2];
                            tmp->dtb_size = 0;
                            tmp->dtb_file = NULL;
                            tmp->master   = chip;
                            tmp->wroteDtb = 0;
                            tmp->master_offset = 0;
                            count++;
                        }
                    }

                    log_err("... skip, incorrect '%s' format\n", dt_tag);
                    break;
                }
            } else if (msmversion == 2) {
                if ((pos = strstr(line, dt_tag)) != NULL) {
                    pos += strlen(dt_tag);

                    entryEndedDT = 0;
                    for (;entryEndedDT < 1;) {
                        entryValidDT = 1;
                        for (i = 0; i < 2; i++) {
                            tok = strtok_r(pos, " \t", &sptr);
                            pos = NULL;
                            if (tok != NULL) {
                                if (*tok == '>') {
                                    entryEndedDT = 1;
                                    entryValidDT = 0;
                                    break;
                                }
                                data_st[i] = strtoul(tok, NULL, 0);
                            } else {
                                data_st[i] = 0;
                                entryValidDT = 0;
                                entryEndedDT = 1;
                            }
                        }

                        if (entryValidDT) {
                            tmp_id = (struct chipId_t *)
                                         malloc(sizeof(struct chipId_t));
                            if (!tmp_id) {
                                log_err("Out of memory\n");
                                break;
                            }
                            if (!chipId) {
                                chipId = tmp_id;
                                cId = tmp_id;
                                chipId->t_next = NULL;
                            } else {
                                tmp_id->t_next = chipId->t_next;
                                chipId->t_next = tmp_id;
                            }
                            tmp_id->chipset = data_st[0];
                            tmp_id->revNum= data_st[1];
                            count1++;
                        }
                    }
                }

                if ((pos = strstr(line,QCDT_BOARD_TAG)) != NULL) {
                    pos += strlen(QCDT_BOARD_TAG);
                    entryEndedST = 0;
                    for (;entryEndedST < 1;) {
                        entryValidST = 1;
                        for (i = 0; i < 2; i++) {
                            tok = strtok_r(pos, " \t", &sptr);
                            pos = NULL;
                            if (tok != NULL) {
                                if (*tok == '>') {
                                    entryEndedST = 1;
                                    entryValidST = 0;
                                    break;
                                }
                                data_st[i] = strtoul(tok, NULL, 0);
                            } else {
                                data_st[i] = 0;
                                entryValidST = 0;
                                entryEndedST = 1;
                            }
                        }
                        if (entryValidST) {
                            tmp_st = (struct chipSt_t *)
                                       malloc(sizeof(struct chipSt_t));
                            if (!tmp_st) {
                                log_err("Out of memory\n");
                                break;
                            }

                            if (!chipSt) {
                                chipSt = tmp_st;
                                cSt = tmp_st;
                                chipSt->t_next = NULL;
                            } else {
                                tmp_st->t_next = chipSt->t_next;
                                chipSt->t_next = tmp_st;
                            }

                            tmp_st->platform = data_st[0];
                            tmp_st->subtype= data_st[1];
                            count2++;
                        }
                    }
                }
            }
        }
    }

    if (line)
        free(line);

    if (force_v2 || msmversion == 2) {

    if (count1 == 0) {
        log_err("... skip, incorrect '%s' format\n", dt_tag);
        return NULL;
    }
    if (count2 == 0) {
        log_err("... skip, incorrect '%s' format\n", QCDT_BOARD_TAG);
        return NULL;
    }

    tmp_st = cSt;
    while (cId != NULL) {
        while (cSt != NULL) {
            tmp = (struct chipInfo_t *)
                      malloc(sizeof(struct chipInfo_t));
            if (!tmp) {
                log_err("Out of memory\n");
                break;
            }
            if (!chip) {
                chip = tmp;
                chip->t_next = NULL;
            } else {
                tmp->t_next = chip->t_next;
                chip->t_next = tmp;
            }

            tmp->chipset  = cId->chipset;
            tmp->platform = cSt->platform;
            tmp->revNum   = cId->revNum;
            tmp->subtype  = cSt->subtype;
            tmp->dtb_size = 0;
            tmp->dtb_file = NULL;
            tmp->master   = chip;
            tmp->wroteDtb = 0;
            tmp->master_offset = 0;

            cSt = cSt->t_next;

        }
        cSt = tmp_st;
        cId = cId->t_next;
    }

    if (entryEndedST  == 1 && entryEndedDT == 1) {
        pclose(pfile);
        *num = count1;
        free(chipSt);
        free(chipId);
        return chip;
    }

    } else {
        pclose(pfile);
    }

    return NULL;
}
Пример #7
0
/* Reads the output of command into buffer then inserts into a MESSAGE struct. */
void nonInteractive_appendClipboardContents( MESSAGE *msg, char *command ) {

    /* Loop to the end of the message */
    msg = msg->root;
    for ( ; msg->next; msg = msg->next )
        ;

    /* Allocate and move to new node */
    msg->next = list_getNode( msg );
    msg = msg->next;

    /* Get and set path and time information */
    list_setPath( msg );
    list_setTime( msg );

    char *tmp, *buffer;
    tmp = buffer = NULL;

    int buffSize, ch, charsRead;
    buffSize = 1024;
    charsRead = 0;

    buffer = malloc( buffSize * sizeof(char) );

    if ( !buffer ) {
        fprintf( stderr,
                "Failed to allocate memory for message buffer in nonInteractive_appendClipboardContents\n" );
        exit( 1 );
    }

    FILE *fp;

    /* Open the command for reading. */
    fp = popen( command, "r" );
    if ( fp == NULL ) {
        printf( "Failed to run command\n" );
        exit( 1 );
    }

    while ( ( ch = fgetc( fp ) ) != EOF ) {

        /* If we've outgrown the buffer then allocate some more memory */
        if ( charsRead >= buffSize ) {
            buffSize *= 2;
            tmp = realloc( buffer, buffSize * sizeof(char *) );

            if ( !tmp ) {
                fprintf( stderr,
                        "Failed to allocate %d bytes in nonInteractive_appendMessage\n",
                        buffSize );
                exit( 1 );
            } else {
                buffer = tmp;
            }
        } else {
            /* Otherwise add the character to the buffer and increment charsRead */
            buffer[charsRead] = ch;
            charsRead++;
        }
    }

    /* Insert the buffer contents into a MESSAGE struct */
    list_insertString( msg, buffer );

    free( buffer );
    pclose( fp );
}
Пример #8
0
bool MapnikRenderer::Preprocess( IImporter* importer, QString dir )
{
	QString filename = fileInDirectory( dir, "Mapnik Renderer" );

	try {
		IImporter::BoundingBox box;
		if ( !importer->GetBoundingBox( &box ) )
			return false;
		std::vector< IImporter::RoutingEdge > inputEdges;
		std::vector< IImporter::RoutingNode > inputNodes;
		std::vector< IImporter::RoutingNode > inputPaths;
		if ( m_settings.deleteTiles ) {
			if ( !importer->GetRoutingEdges( &inputEdges ) ) {
				qCritical() << "Mapnik Renderer: failed to read routing edges";
				return false;
			}
			if ( !importer->GetRoutingNodes( &inputNodes ) ) {
				qCritical() << "Mapnik Renderer: failed to read routing nodes";
				return false;
			}
			if ( !importer->GetRoutingEdgePaths( &inputPaths ) ) {
				qCritical() << "Mapnik Renderer: failed to read routing paths";
			}
		}

		Timer time;

		mapnik::datasource_cache::instance().register_datasources( m_settings.plugins.toLatin1().constData() );
		QDir fonts( m_settings.fonts );
		mapnik::projection projection( "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" );
		mapnik::freetype_engine::register_font( fonts.filePath( "DejaVuSans.ttf" ).toLatin1().constData() );
		mapnik::freetype_engine::register_font( fonts.filePath( "DejaVuSans-Bold.ttf" ).toLatin1().constData() );
		mapnik::freetype_engine::register_font( fonts.filePath( "DejaVuSans-Oblique.ttf" ).toLatin1().constData() );
		mapnik::freetype_engine::register_font( fonts.filePath( "DejaVuSans-BoldOblique.ttf" ).toLatin1().constData() );

		qDebug() << "Mapnik Renderer: initialized mapnik connection:" << time.restart() << "ms";

		int numThreads = omp_get_max_threads();
		qDebug() << "Mapnik Renderer: using" << numThreads << "threads";

		qDebug() << "Mapnik Renderer: x: " << box.min.x << "-" << box.max.x;
		qDebug() << "Mapnik Renderer: y: " << box.min.y << "-" << box.max.y;

		FileStream configData( filename );
		if ( !configData.open( QIODevice::WriteOnly ) )
			return false;

		configData << quint32( m_settings.tileSize ) << quint32( m_settings.zoomLevels.size() );

		long long tilesSkipped = 0;
		long long tiles = 0;
		long long metaTilesRendered = 0;
		long long pngcrushSaved = 0;

		std::vector< ZoomInfo > zoomInfo( m_settings.zoomLevels.size() );
		std::vector< MetaTile > tasks;

		for ( int zoomLevel = 0; zoomLevel < ( int ) m_settings.zoomLevels.size(); zoomLevel++ ) {
			ZoomInfo& info = zoomInfo[zoomLevel];
			int zoom = m_settings.zoomLevels[zoomLevel];

			info.minX = box.min.GetTileX( zoom );
			info.maxX = box.max.GetTileX( zoom ) + 1;
			info.minY = box.min.GetTileY( zoom );
			info.maxY = box.max.GetTileY( zoom ) + 1;

			if ( zoom <= m_settings.fullZoom ) {
				info.minX = info.minY = 0;
				info.maxX = info.maxY = 1 << zoom;
			} else {
				info.minX = std::max( 0 , info.minX - m_settings.tileMargin );
				info.maxX = std::min ( 1 << zoom, info.maxX + m_settings.tileMargin );
				info.minY = std::max( 0, info.minY - m_settings.tileMargin );
				info.maxY = std::min ( 1 << zoom, info.maxY + m_settings.tileMargin );
			}

			tiles += ( info.maxX - info.minX ) * ( info.maxY - info.minY );
			qDebug() << "Mapnik Renderer: [" << zoom << "] x:" << info.minX << "-" << info.maxX << "; y:" << info.minY << "-" << info.maxY;
			configData << quint32( zoom ) << quint32( info.minX ) << quint32( info.maxX ) << quint32( info.minY ) << quint32( info.maxY );

			int numberOfTiles = ( info.maxX - info.minX ) * ( info.maxY - info.minY );
			IndexElement dummyIndex;
			dummyIndex.start = dummyIndex.size = 0;
			info.index.resize( numberOfTiles, dummyIndex );

			std::vector< UnsignedCoordinate > path;
			for ( std::vector< IImporter::RoutingEdge >::const_iterator i = inputEdges.begin(), e = inputEdges.end(); i != e; ++i ) {
				path.push_back( inputNodes[i->source].coordinate );
				for ( int pathID = 0; pathID < i->pathLength; pathID++ )
					path.push_back( inputPaths[pathID + i->pathID].coordinate );
				path.push_back( inputNodes[i->target].coordinate );

				for ( unsigned edge = 0; edge < path.size(); edge++ ) {
					int sourceX = path[edge].GetTileX( zoom );
					int sourceY = path[edge].GetTileY( zoom );
					int targetX = path[edge].GetTileX( zoom );
					int targetY = path[edge].GetTileY( zoom );
					if ( sourceX > targetX )
						std::swap( sourceX, targetX );
					if ( sourceY > targetY )
						std::swap( sourceY, targetY );
					sourceX = std::max( sourceX, info.minX );
					sourceX = std::min( sourceX, info.maxX - 1 );
					sourceY = std::max( sourceY, info.minY );
					sourceY = std::min( sourceY, info.maxY - 1 );
					targetX = std::max( targetX, info.minX );
					targetX = std::min( targetX, info.maxX - 1 );
					targetY = std::max( targetY, info.minY );
					targetY = std::min( targetY, info.maxY - 1 );
					for ( int x = sourceX; x <= targetX; ++x )
						for ( int y = sourceY; y <= targetY; ++y )
							info.index[( x - info.minX ) + ( y - info.minY ) * ( info.maxX - info.minX )].size = 1;
				}

				path.clear();
			}

			info.tilesFile = new QFile( filename + QString( "_%1_tiles" ).arg( zoom ) );
			if ( !openQFile( info.tilesFile, QIODevice::WriteOnly ) )
				return false;

			for ( int x = info.minX; x < info.maxX; x+= m_settings.metaTileSize ) {
				int metaTileSizeX = std::min( m_settings.metaTileSize, info.maxX - x );
				for ( int y = info.minY; y < info.maxY; y+= m_settings.metaTileSize ) {
					int metaTileSizeY = std::min( m_settings.metaTileSize, info.maxY - y );
					MetaTile tile;
					tile.zoom = zoomLevel;
					tile.x = x;
					tile.y = y;
					tile.metaTileSizeX = metaTileSizeX;
					tile.metaTileSizeY = metaTileSizeY;
					tasks.push_back( tile );
				}
			}
		}


#pragma omp parallel
		{
			int threadID = omp_get_thread_num();
			const int metaTileSize = m_settings.metaTileSize * m_settings.tileSize + 2 * m_settings.margin;

			mapnik::Map map;
			mapnik::image_32 image( metaTileSize, metaTileSize );
			QTemporaryFile tempOut;
			QTemporaryFile tempIn;
			mapnik::load_map( map, m_settings.theme.toLocal8Bit().constData() );

#pragma omp for schedule( dynamic )
			for ( int i = 0; i < ( int ) tasks.size(); i++ ) {

				int metaTileSizeX = tasks[i].metaTileSizeX;
				int metaTileSizeY = tasks[i].metaTileSizeY;
				int x = tasks[i].x;
				int y = tasks[i].y;
				int zoomLevel = tasks[i].zoom;
				int zoom = m_settings.zoomLevels[zoomLevel];
				ZoomInfo& info = zoomInfo[zoomLevel];

				map.resize( metaTileSizeX * m_settings.tileSize + 2 * m_settings.margin, metaTileSizeY * m_settings.tileSize + 2 * m_settings.margin );

				ProjectedCoordinate drawTopLeft( x - 1.0 * m_settings.margin / m_settings.tileSize, y - 1.0 * m_settings.margin / m_settings.tileSize, zoom );
				ProjectedCoordinate drawBottomRight( x + metaTileSizeX + 1.0 * m_settings.margin / m_settings.tileSize, y + metaTileSizeY + 1.0 * m_settings.margin / m_settings.tileSize, zoom );
				GPSCoordinate drawTopLeftGPS = drawTopLeft.ToGPSCoordinate();
				GPSCoordinate drawBottomRightGPS = drawBottomRight.ToGPSCoordinate();
				projection.forward( drawTopLeftGPS.longitude, drawBottomRightGPS.latitude );
				projection.forward( drawBottomRightGPS.longitude, drawTopLeftGPS.latitude );
				mapnik::box2d<double> boundingBox( drawTopLeftGPS.longitude, drawTopLeftGPS.latitude, drawBottomRightGPS.longitude, drawBottomRightGPS.latitude );
				map.zoom_to_box( boundingBox );
				mapnik::agg_renderer<mapnik::image_32> renderer( map, image );
				renderer.apply();

				std::string data;
				int skipped = 0;
				int saved = 0;
				for ( int subX = 0; subX < metaTileSizeX; ++subX ) {
					for ( int subY = 0; subY < metaTileSizeY; ++subY ) {
						int indexNumber = ( y + subY - info.minY ) * ( info.maxX - info.minX ) + x + subX - info.minX;
						mapnik::image_view<mapnik::image_data_32> view = image.get_view( subX * m_settings.tileSize + m_settings.margin, subY * m_settings.tileSize + m_settings.margin, m_settings.tileSize, m_settings.tileSize );
						std::string result;
						if ( !m_settings.deleteTiles || info.index[( x + subX - info.minX ) + ( y + subY - info.minY ) * ( info.maxX - info.minX )].size == 1 ) {
							if ( m_settings.reduceColors )
								result = mapnik::save_to_string( view, "png256" );
							else
								result = mapnik::save_to_string( view, "png" );

							if ( m_settings.pngcrush ) {
								tempOut.open();
								tempOut.write( result.data(), result.size() );
								tempOut.flush();
								tempIn.open();
								pclose( popen( ( "pngcrush " + tempOut.fileName() + " " + tempIn.fileName() ).toUtf8().constData(), "r" ) );
								QByteArray buffer = tempIn.readAll();
								tempIn.close();
								tempOut.close();
								if ( buffer.size() != 0 && buffer.size() < ( int ) result.size() ) {
									saved += result.size() - buffer.size();
									result.assign( buffer.constData(), buffer.size() );
								}
							}
						}

						info.index[indexNumber].start = data.size();
						info.index[indexNumber].size = result.size();
						data += result;
					}
				}

				qint64 position;
#pragma omp critical
				{
					position = info.tilesFile->pos();
					info.tilesFile->write( data.data(), data.size() );

					metaTilesRendered++;
					tilesSkipped += skipped;
					pngcrushSaved += saved;
					qDebug() << "Mapnik Renderer: [" << zoom << "], thread" << threadID << ", metatiles:" << metaTilesRendered << "/" << tasks.size();
				}

				for ( int subX = 0; subX < metaTileSizeX; ++subX ) {
					for ( int subY = 0; subY < metaTileSizeY; ++subY ) {
						int indexNumber = ( y + subY - info.minY ) * ( info.maxX - info.minX ) + x + subX - info.minX;
						info.index[indexNumber].start += position;
					}
				}
			}
		}

		for ( int zoomLevel = 0; zoomLevel < ( int ) m_settings.zoomLevels.size(); zoomLevel++ ) {
			const ZoomInfo& info = zoomInfo[zoomLevel];
			int zoom = m_settings.zoomLevels[zoomLevel];
			QFile indexFile( filename + QString( "_%1_index" ).arg( zoom ) );
			if ( !openQFile( &indexFile, QIODevice::WriteOnly ) )
				return false;
			for ( int i = 0; i < ( int ) info.index.size(); i++ ) {
				indexFile.write( ( const char* ) &info.index[i].start, sizeof( info.index[i].start ) );
				indexFile.write( ( const char* ) &info.index[i].size, sizeof( info.index[i].size ) );
			}
			delete info.tilesFile;
		}

		if ( m_settings.deleteTiles )
			qDebug() << "Mapnik Renderer: removed" << tilesSkipped << "tiles";
		if ( m_settings.pngcrush )
			qDebug() << "Mapnik Renderer: PNGcrush saved" << pngcrushSaved / 1024 / 1024 << "MB";

		qDebug() << "Mapnik Renderer: finished:" << time.restart() << "ms";

	} catch ( const mapnik::config_error & ex ) {
		qCritical( "Mapnik Renderer: ### Configuration error: %s", ex.what() );
		return false;
	} catch ( const std::exception & ex ) {
		qCritical( "Mapnik Renderer: ### STD error: %s", ex.what() );
		return false;
	} catch ( ... ) {
		qCritical( "Mapnik Renderer: ### Unknown error" );
		return false;
	}
	return true;
}
/* UtvGetSystemStats
   Populates a CJSON struct with relevant system stats information
*/
UTV_RESULT UtvPlatformGetSystemStats( void* pVoidResponseData )
{
  UTV_RESULT result = UTV_OK;
  UTV_INT8 ubReadBuffer[1024];
  FILE* fpVmStat;
  UTV_UINT32 uiVmStatVer = 0;
  FILE* fp;
  UTV_UINT32 uiScanCount = 0;
  UTV_UINT32 uiMemFree = 0;
  UTV_UINT32 uiMemUsed = 0;
  UTV_UINT32 uiMemTotal = 0;
  UTV_UINT32 uiMemPercentUsed = 0;
  UTV_UINT32 uiCpuUser = 0;
  UTV_UINT32 uiCpuSystem = 0;
  UTV_UINT32 uiCpuTotalUsed = 0;
  cJSON* responseData = (cJSON*)pVoidResponseData;
  cJSON* memObject = NULL;
  cJSON* cpuObject = NULL;

  if (NULL != responseData)
  {
    memset(ubReadBuffer, 0x00, sizeof(ubReadBuffer));

    /* Get stats */
    fpVmStat = popen( "vmstat", "r" );

    if ( !fpVmStat )
    {
      result = UTV_FILE_OPEN_FAILS;
    }
    else
    {
      /* Parse first 2 headers... ignore this data */
      fgets( ubReadBuffer, sizeof(ubReadBuffer), fpVmStat );
      fgets( ubReadBuffer, sizeof(ubReadBuffer), fpVmStat );

      if ( 0 == strncmp( ubReadBuffer, " r  b  w", strlen( " r  b  w" ) ) )
      {
        uiVmStatVer = 2;
      }
      else if ( 0 == strncmp( ubReadBuffer, " r  b   swpd", strlen( " r  b   swpd" ) ) )
      {
        uiVmStatVer = 3;
      }

      /* Parse actual stats */
      fgets( ubReadBuffer, sizeof(ubReadBuffer), fpVmStat );

      if ( 2 == uiVmStatVer )
      {
        uiScanCount = sscanf( ubReadBuffer,
                              "%*u %*u %*u %*u %lu %*u %*u %*u %*u %*u %*u %*u %*u %lu %lu",
                              &uiMemFree,
                              &uiCpuUser,
                              &uiCpuSystem );
      }
      else if ( 3 == uiVmStatVer )
      {
        uiScanCount = sscanf( ubReadBuffer,
                              "%*u %*u %*u %lu %*u %*u %*u %*u %*u %*u %*u %*u %lu %lu",
                              &uiMemFree,
                              &uiCpuUser,
                              &uiCpuSystem );
      }

      if ( 3 != uiScanCount )
      {
        result = UTV_READ_FAILS;
      }
      else
      {
        /* Calculate total used CPU */
        uiCpuTotalUsed = uiCpuUser + uiCpuSystem;
      }
                      
      pclose( fpVmStat );
      fpVmStat = NULL;

      fp = fopen( "/proc/meminfo", "r" );

      if ( !fp )
      {
        result = UTV_FILE_OPEN_FAILS;
      }
      else
      {
        /* Parse lines */
        fgets( ubReadBuffer, sizeof(ubReadBuffer), fp );

        if ( 0 == sscanf( ubReadBuffer, "MemTotal: %lu", &uiMemTotal ) )
        {
          result = UTV_READ_FAILS;
        }
        else
        {
          /* Calculate memory percentage */
          if ( 0 != uiMemTotal )
          {
            uiMemUsed = uiMemTotal - uiMemFree;
            uiMemPercentUsed = round( ((float)uiMemUsed / (float)uiMemTotal) * 100 );
  
            /* Populate JSON object */
            memObject = cJSON_CreateObject();
            cpuObject = cJSON_CreateObject();

            cJSON_AddNumberToObject( memObject, "Percent Used", uiMemPercentUsed );
            cJSON_AddNumberToObject( memObject, "Free (MB)", uiMemFree );
            cJSON_AddNumberToObject( memObject, "Used (MB)", uiMemUsed );
            cJSON_AddNumberToObject( memObject, "Total (MB)", uiMemTotal );
            
            cJSON_AddNumberToObject( cpuObject, "Total Percent Used", uiCpuTotalUsed );
            cJSON_AddNumberToObject( cpuObject, "User Percent Used", uiCpuUser );
            cJSON_AddNumberToObject( cpuObject, "System Percent Used", uiCpuSystem );

            cJSON_AddItemToObject( responseData, "Memory", memObject );
            cJSON_AddItemToObject( responseData, "CPU", cpuObject );
          }
        }

        fclose( fp );
      }
    }
  }
  else
  {
    result = UTV_INVALID_PARAMETER;
  }
 
  return ( result );
}
Пример #10
0
int main(int argc, char *argv[])
{
	int rtn;
	int v;

	FILE *fp;
	unsigned char b[S_BUF];
	char *tp;

	int i_port_no;
	int shtdwn;

	struct option long_opts[] = {
		{"input",	1, NULL, 0},
		{"time",	1, NULL, 1},
		{0, 0, 0, 0}
	};

	int res = 0;
	int idx = 0;

	while((res = getopt_long_only(argc, argv, "it", long_opts, &idx)) != EOD) {
		switch(res) {
		case 0:	/* input */
			DPRINT("input opt\n");
			DPRINT("name=%s val=%s\n",long_opts[idx].name, optarg);
			i_port_no = atoi(optarg);
			if(i_port_no == 0) { /* 0 : not number */
				fprintf(stderr, "Parameter not number : %s\n",optarg);
			}
			break;
		case 1: /* time */
			DPRINT("time opt\n");
			DPRINT("name=%s val=%s\n",long_opts[idx].name, optarg);
			shtdwn = atoi(optarg);
			if(shtdwn == 0) { /* 0 : not number */
				fprintf(stderr, "Parameter not number : %s\n",optarg);
			}
			break;
		case 'i':
		case 't':
			break;
		}
	}

	DPRINT("idx=%d\n",idx);

	if( argc == 1 ) {
		/* default */
		i_port_no = INPUT_PORT;
		shtdwn = SHTDWN;
	} else {
		if(idx == 0 || i_port_no == 0 || shtdwn == 0) {
			fprintf(stderr, "Usage:%s\n",CMDNAME);
			fprintf(stderr, "      %s --input <port No.> --time <shutdown>\n",CMDNAME);
			fprintf(stderr, "      %s --input=<port No.> --time=<shutdown>\n",CMDNAME);
			fprintf(stderr, "  (default:--input 24 --time 30)\n");
			return 1;
		}
	}

	/* No allow dup run */
	memset(b,0,S_BUF);
	DPRINT("PSNAME=%s\n",PSNAME);
	fp = popen(PSNAME, "r");
	if(fp == NULL) {
		fprintf(stderr, "fopen():Open Error.\n");
		return 1;
	} else {
		/*fgets(b, S_BUF, fp);*/
		fread(b, 1, S_BUF, fp);
		pclose(fp);
		DPRINT("val:\n%s",b);
		tp = strstr(b, CMDNAME);
		DPRINT("tp:\n%s",tp);
		DPRINT("strlen(tp)=%d\n",strlen(tp));
		if(strlen(tp) == strlen(CMDNAME)+1) {
			DPRINT("One Process running.\n");
		} else {
			/* No allow dup run */
			fprintf(stderr, "Two Processes running Error. Stop.\n");
			return 0;	/* normal */
		}
	}

	rtn = wiringPiSetupGpio();
	if( rtn == -1 ) {
		fprintf(stderr, "wiringPiSetupGpio(): Error (%d)\n", rtn);
		return 1;
	}

	pullUpDnControl(i_port_no, PUD_UP); /* pullup */
	pinMode(i_port_no, INPUT); 

	v = 0;  
	v = digitalRead(i_port_no);
	DPRINT("val=%d\n", v);

	/* SW ON */
	if(v == 0) {	/* 0=ON 1=OFF:because pullup */
		sleep(shtdwn);
		system("/usr/bin/sudo /sbin/shutdown -h now");
	}

	return 0;
}
Пример #11
0
 // dtor closes the pipe
 ~wxStdioPipe()
 {
     if ( m_fp )
         pclose(m_fp);
 }
Пример #12
0
int
convert (DB_playItem_t *it, const char *outfolder, const char *outfile, int output_bps, int output_is_float, int preserve_folder_structure, const char *root_folder, ddb_encoder_preset_t *encoder_preset, ddb_dsp_preset_t *dsp_preset, int *abort) {
    if (deadbeef->pl_get_item_duration (it) <= 0) {
        deadbeef->pl_lock ();
        const char *fname = deadbeef->pl_find_meta (it, ":URI");
        fprintf (stderr, "converter: stream %s doesn't have finite length, skipped\n", fname);
        deadbeef->pl_unlock ();
        return -1;
    }

    char *path = outfolder[0] ? strdupa (outfolder) : strdupa (getenv("HOME"));
    if (!check_dir (path, 0755)) {
        fprintf (stderr, "converter: failed to create output folder: %s\n", outfolder);
        return -1;
    }

    int err = -1;
    FILE *enc_pipe = NULL;
    FILE *temp_file = NULL;
    DB_decoder_t *dec = NULL;
    DB_fileinfo_t *fileinfo = NULL;
    char out[PATH_MAX] = ""; // full path to output file
    char input_file_name[PATH_MAX] = "";
    dec = (DB_decoder_t *)deadbeef->plug_get_for_id (deadbeef->pl_find_meta (it, ":DECODER"));

    if (dec) {
        fileinfo = dec->open (0);
        if (fileinfo && dec->init (fileinfo, DB_PLAYITEM (it)) != 0) {
            deadbeef->pl_lock ();
            fprintf (stderr, "converter: failed to decode file %s\n", deadbeef->pl_find_meta (it, ":URI"));
            deadbeef->pl_unlock ();
            goto error;
        }
        if (fileinfo) {
            if (output_bps == -1) {
                output_bps = fileinfo->fmt.bps;
                output_is_float = fileinfo->fmt.is_float;
            }

            get_output_path (it, outfolder, outfile, encoder_preset, out, sizeof (out));
            if (encoder_preset->method == DDB_ENCODER_METHOD_FILE) {
                const char *tmp = getenv ("TMPDIR");
                if (!tmp) {
                    tmp = "/tmp";
                }
                snprintf (input_file_name, sizeof (input_file_name), "%s/ddbconvXXXXXX", tmp);
                mktemp (input_file_name);
                strcat (input_file_name, ".wav");
            }
            else {
                strcpy (input_file_name, "-");
            }

            char enc[2000];
            memset (enc, 0, sizeof (enc));

            // formatting: %o = outfile, %i = infile
            char *e = encoder_preset->encoder;
            char *o = enc;
            *o = 0;
            int len = sizeof (enc);
            while (e && *e) {
                if (len <= 0) {
                    fprintf (stderr, "converter: failed to assemble encoder command line - buffer is not big enough, try to shorten your parameters. max allowed length is %u characters\n", (unsigned)sizeof (enc));
                    goto error;
                }
                if (e[0] == '%' && e[1]) {
                    if (e[1] == 'o') {
                        int l = snprintf (o, len, "\"%s\"", out);
                        o += l;
                        len -= l;
                    }
                    else if (e[1] == 'i') {
                        int l = snprintf (o, len, "\"%s\"", input_file_name);
                        o += l;
                        len -= l;
                    }
                    else {
                        strncpy (o, e, 2);
                        o += 2;
                        len -= 2;
                    }
                    e += 2;
                }
                else {
                    *o++ = *e++;
                    *o = 0;
                    len--;
                }
            }

            fprintf (stderr, "converter: will encode using: %s\n", enc[0] ? enc : "internal RIFF WAVE writer");

            if (!encoder_preset->encoder[0]) {
                // write to wave file
                temp_file = fopen (out, "w+b");
                if (!temp_file) {
                    fprintf (stderr, "converter: failed to open output wave file %s\n", out);
                    goto error;
                }
            }
            else if (encoder_preset->method == DDB_ENCODER_METHOD_FILE) {
                temp_file = fopen (input_file_name, "w+b");
                if (!temp_file) {
                    fprintf (stderr, "converter: failed to open temp file %s\n", input_file_name);
                    goto error;
                }
            }
            else {
                enc_pipe = popen (enc, "w");
                if (!enc_pipe) {
                    fprintf (stderr, "converter: failed to open encoder\n");
                    goto error;
                }
            }

            if (!temp_file) {
                temp_file = enc_pipe;
            }

            // write wave header
            char wavehdr_int[] = {
                0x52, 0x49, 0x46, 0x46, 0x24, 0x70, 0x0d, 0x00, 0x57, 0x41, 0x56, 0x45, 0x66, 0x6d, 0x74, 0x20, 0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x44, 0xac, 0x00, 0x00, 0x10, 0xb1, 0x02, 0x00, 0x04, 0x00, 0x10, 0x00, 0x64, 0x61, 0x74, 0x61
            };
            char wavehdr_float[] = {
                0x52, 0x49, 0x46, 0x46, 0x2a, 0xdf, 0x02, 0x00, 0x57, 0x41, 0x56, 0x45, 0x66, 0x6d, 0x74, 0x20, 0x28, 0x00, 0x00, 0x00, 0xfe, 0xff, 0x02, 0x00, 0x40, 0x1f, 0x00, 0x00, 0x00, 0xfa, 0x00, 0x00, 0x08, 0x00, 0x20, 0x00, 0x16, 0x00, 0x20, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71, 0x66, 0x61, 0x63, 0x74, 0x04, 0x00, 0x00, 0x00, 0xc5, 0x5b, 0x00, 0x00, 0x64, 0x61, 0x74, 0x61
            };
            char *wavehdr = output_is_float ? wavehdr_float : wavehdr_int;
            int wavehdr_size = output_is_float ? sizeof (wavehdr_float) : sizeof (wavehdr_int);
            int header_written = 0;
            uint32_t outsize = 0;
            uint32_t outsr = fileinfo->fmt.samplerate;
            uint16_t outch = fileinfo->fmt.channels;

            int samplesize = fileinfo->fmt.channels * fileinfo->fmt.bps / 8;
            int bs = 10250 * samplesize;
            char buffer[bs * 4];
            int dspsize = bs / samplesize * sizeof (float) * fileinfo->fmt.channels;
            char dspbuffer[dspsize * 4];
            int eof = 0;
            for (;;) {
                if (eof) {
                    break;
                }
                if (abort && *abort) {
                    break;
                }
                int sz = dec->read (fileinfo, buffer, bs);

                if (sz != bs) {
                    eof = 1;
                }
                if (dsp_preset) {
                    ddb_waveformat_t fmt;
                    ddb_waveformat_t outfmt;
                    memcpy (&fmt, &fileinfo->fmt, sizeof (fmt));
                    memcpy (&outfmt, &fileinfo->fmt, sizeof (fmt));
                    fmt.bps = 32;
                    fmt.is_float = 1;
                    deadbeef->pcm_convert (&fileinfo->fmt, buffer, &fmt, dspbuffer, sz);

                    ddb_dsp_context_t *dsp = dsp_preset->chain;
                    int frames = sz / samplesize;
                    while (dsp) {
                        frames = dsp->plugin->process (dsp, (float *)dspbuffer, frames, sizeof (dspbuffer) / (fmt.channels * 4), &fmt, NULL);
                        dsp = dsp->next;
                    }

                    outsr = fmt.samplerate;
                    outch = fmt.channels;

                    outfmt.bps = output_bps;
                    outfmt.is_float = output_is_float;
                    outfmt.channels = outch;
                    outfmt.samplerate = outsr;

                    int n = deadbeef->pcm_convert (&fmt, dspbuffer, &outfmt, buffer, frames * sizeof (float) * fmt.channels);
                    sz = n;
                }
                else if (fileinfo->fmt.bps != output_bps || fileinfo->fmt.is_float != output_is_float) {
                    ddb_waveformat_t outfmt;
                    memcpy (&outfmt, &fileinfo->fmt, sizeof (outfmt));
                    outfmt.bps = output_bps;
                    outfmt.is_float = output_is_float;
                    outfmt.channels = outch;
                    outfmt.samplerate = outsr;

                    int frames = sz / samplesize;
                    int n = deadbeef->pcm_convert (&fileinfo->fmt, buffer, &outfmt, dspbuffer, frames * samplesize);
                    memcpy (buffer, dspbuffer, n);
                    sz = n;
                }
                outsize += sz;

                if (!header_written) {
                    uint32_t size = (it->endsample-it->startsample) * outch * output_bps / 8;
                    if (!size) {
                        size = deadbeef->pl_get_item_duration (it) * fileinfo->fmt.samplerate * outch * output_bps / 8;

                    }

                    if (outsr != fileinfo->fmt.samplerate) {
                        uint64_t temp = size;
                        temp *= outsr;
                        temp /= fileinfo->fmt.samplerate;
                        size  = temp;
                    }

                    memcpy (&wavehdr[22], &outch, 2);
                    memcpy (&wavehdr[24], &outsr, 4);
                    uint16_t blockalign = outch * output_bps / 8;
                    memcpy (&wavehdr[32], &blockalign, 2);
                    memcpy (&wavehdr[34], &output_bps, 2);

                    fwrite (wavehdr, 1, wavehdr_size, temp_file);
                    if (encoder_preset->method == DDB_ENCODER_METHOD_PIPE) {
                        size = 0;
                    }
                    fwrite (&size, 1, sizeof (size), temp_file);
                    header_written = 1;
                }

                int64_t res = fwrite (buffer, 1, sz, temp_file);
                if (sz != res) {
                    fprintf (stderr, "converter: write error (%lld bytes written out of %d)\n", res, sz);
                    goto error;
                }
            }
            if (abort && *abort) {
                goto error;
            }
            if (temp_file && temp_file != enc_pipe) {
                fseek (temp_file, wavehdr_size, SEEK_SET);
                fwrite (&outsize, 1, 4, temp_file);

                fclose (temp_file);
                temp_file = NULL;
            }

            if (encoder_preset->encoder[0] && encoder_preset->method == DDB_ENCODER_METHOD_FILE) {
                enc_pipe = popen (enc, "w");
            }
        }
    }
    err = 0;
error:
    if (temp_file && temp_file != enc_pipe) {
        fclose (temp_file);
        temp_file = NULL;
    }
    if (enc_pipe) {
        pclose (enc_pipe);
        enc_pipe = NULL;
    }
    if (dec && fileinfo) {
        dec->free (fileinfo);
        fileinfo = NULL;
    }
    if (abort && *abort && out[0]) {
        unlink (out);
    }
    if (input_file_name[0] && strcmp (input_file_name, "-")) {
        unlink (input_file_name);
    }

    // write junklib tags
    uint32_t tagflags = JUNK_STRIP_ID3V2 | JUNK_STRIP_APEV2 | JUNK_STRIP_ID3V1;
    if (encoder_preset->tag_id3v2) {
        tagflags |= JUNK_WRITE_ID3V2;
    }
    if (encoder_preset->tag_id3v1) {
        tagflags |= JUNK_WRITE_ID3V1;
    }
    if (encoder_preset->tag_apev2) {
        tagflags |= JUNK_WRITE_APEV2;
    }
    DB_playItem_t *out_it = deadbeef->pl_item_alloc ();
    deadbeef->pl_item_copy (out_it, it);
    deadbeef->pl_replace_meta (out_it, ":URI", out);
    deadbeef->pl_delete_meta (out_it, "cuesheet");

    deadbeef->junk_rewrite_tags (out_it, tagflags, encoder_preset->id3v2_version + 3, "iso8859-1");

    // write flac tags
    if (encoder_preset->tag_flac) {
        // find flac decoder plugin
        DB_decoder_t **plugs = deadbeef->plug_get_decoder_list ();
        DB_decoder_t *flac = NULL;
        for (int i = 0; plugs[i]; i++) {
            if (!strcmp (plugs[i]->plugin.id, "stdflac")) {
                flac = plugs[i];
                break;
            }
        }
        if (!flac) {
            fprintf (stderr, "converter: flac plugin not found, cannot write flac metadata\n");
        }
        else {
            if (0 != flac->write_metadata (out_it)) {
                fprintf (stderr, "converter: failed to write flac metadata, not a flac file?\n");
            }
        }
    }

    // write vorbis tags
    if (encoder_preset->tag_oggvorbis) {
        // find flac decoder plugin
        DB_decoder_t **plugs = deadbeef->plug_get_decoder_list ();
        DB_decoder_t *ogg = NULL;
        for (int i = 0; plugs[i]; i++) {
            if (!strcmp (plugs[i]->plugin.id, "stdogg")) {
                ogg = plugs[i];
                break;
            }
        }
        if (!ogg) {
            fprintf (stderr, "converter: ogg plugin not found, cannot write ogg metadata\n");
        }
        else {
            if (0 != ogg->write_metadata (out_it)) {
                fprintf (stderr, "converter: failed to write ogg metadata, not an ogg file?\n");
            }
        }
    }

    deadbeef->pl_item_unref (out_it);


    return err;
}
Пример #13
0
KaldiStream::~KaldiStream() {
  if (_ffid) pclose(_ffid);
  if (_lfid) pclose(_lfid);
}
Пример #14
0
bool wine_start(char *wine_app, char *avsloader, AVS_PIPES *avs_pipes, int pipe_timeout)
{
  char sname[MAX_PATH];
  struct stat st;
  sprintf(sname, "%s %s %d", wine_app, avsloader, pipe_timeout);

  FILE *pfile = popen(sname, "r");
  if (!pfile)
  {
   DEBUG_PRINTF_RED("avsfilter : popen failed, errno %d, failed start app is : [%s]\n", errno, sname);
   return false;
  }

  if (fscanf(pfile, "%s\n", sname) != 1 ||
      stat(sname, &st) ||
      !S_ISDIR(st.st_mode))
  {
    DEBUG_PRINTF_RED("avsfilter : tmpdirname [%s] failed, errno %d[stat %d isdir %d]\n", sname, errno, stat(sname, &st), S_ISDIR(st.st_mode));
    pclose(pfile);
    return false;
  }

  DEBUG_PRINTF("avsfilter : good tmpdirname %s\n", sname);

  if (!init_pipes(avs_pipes, CMD_PIPE_NUM, pfile))
  {
    DEBUG_PRINTF_RED("init_pipes failed\n");
    pclose(pfile);
    return false;
  }

  time_t t = time(NULL);
  DEBUG_PRINTF("avsfilter : precreate thread time %s\n",
         ctime(&t));
  pthread_t thread;
  TPARSER tp = { avs_pipes, pfile };

  open_pipes_ok = false;

  if (pthread_create(&thread, NULL, parse_wine_stdout, &tp))
  {
    DEBUG_PRINTF_RED("Cannot pthread started...Errno %d\n",errno);
    deinit_pipes(avs_pipes, CMD_PIPE_NUM);
    return false;
  }

  t = time(NULL);
  DEBUG_PRINTF("avsfilter : preopen time %s\n",
         ctime(&t));

  if (!open_pipes(avs_pipes, CMD_PIPE_NUM) || wine_loader_down)
  {
    open_pipes_ok = true;
    DEBUG_PRINTF_RED("open_pipes failed\n");
    deinit_pipes(avs_pipes, CMD_PIPE_NUM);
    return false;
  }

  open_pipes_ok = true;

  if (pipe_test_filter (avs_pipes[PIPE_LOADER_READ].hpipe,
                        avs_pipes[PIPE_FILTER_WRITE].hpipe))
  {
    DEBUG_PRINTF("avsfilter : test pipe to filter ok\n");

    if (pipe_test_filter (avs_pipes[PIPE_LOADER_READ].hpipe,
                          avs_pipes[PIPE_LOADER_WRITE].hpipe))
    {
      DEBUG_PRINTF("avsfilter : test pipe to loader ok\n");
    }
    else
      goto error_pipe_test;
  }
  else
  {
    error_pipe_test:
    DEBUG_PRINTF_RED("Error test read/write pipes\n");
    deinit_pipes(avs_pipes, CMD_PIPE_NUM);
    return false;
  }

  DEBUG_PRINTF("wine start is ok\n");
  return true;
}
Пример #15
0
int get_suggested_omp_num_threads() {

  int default_num_threads=1, suggested_num_threads=1;
  
  char* env_var_c;
  env_var_c = getenv ("OMP_NUM_THREADS");
  if(env_var_c) 
    {
      return atoi(env_var_c);
    }
  //    cout<<"OMP_NUM_THREADS is not defined"<<endl;
  
  //set number of threads for appropriate OS
  int avload, nbofproc=omp_get_num_procs();
  FILE *iff;
    
#if defined(__APPLE__) || defined(__MACH__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__bsdi__) || defined(__DragonFly__)
  cout<<"is MAC/*BSD"<<endl;
  iff= popen("echo $(sysctl -n vm.loadavg|cut -d\" \" -f2)", "r");
  if (!iff)
    {
      return default_num_threads;
    }
      
#elif defined(__linux__) || defined(__gnu_linux__) || defined(linux)
  iff= popen("cat /proc/loadavg |cut -d\" \" -f2", "r");
  if (!iff)
    {
      return default_num_threads;
    }
   
#elif defined (__unix) || (__unix__)
  iff=freopen("/proc/loadavg","r",stderr);
  fclose(stderr);
  if(!iff)
    {
      cout<<"your OS is not supported"<<endl;
      return default_num_threads;
    }
  iff= popen("cat /proc/loadavg 2>/dev/null|cut -d\" \" -f2", "r");
  if (!iff)
    {
      return default_num_threads;
    }

#elif defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__)
  iff= popen("wmic cpu get loadpercentage|more +1", "r");
  if (!iff)
    {
      return default_num_threads;
    }
  char buffer[4];
  char* c;
  c=fgets(buffer, sizeof(buffer), iff);
  if(!c)
    {
      return default_num_threads;
    }
  pclose(iff);
  int cout=0;
  while(buffer[count]!='\0' && buffer[count]!=' ')count++;
  for(int i=1,j=1;i<=count;i++,j*=10)
    avload+=(buffer[count-i]-'0')*j;
  suggested_num_threads=nbofproc-(int)(avload*((float)nbofproc/100)+0.5);
  return suggested_num_threads;

#else 
  cout<<"Can't define your OS"<<endl;
  return default_num_threads;
#endif

  char buffer[4];
  char* c;
  c=fgets(buffer, sizeof(buffer), iff);
  if(!c)
    {
      return default_num_threads;
    }
  pclose(iff);
  avload=(buffer[0]-'0')+((buffer[2]-'0')>5?1:0);

  suggested_num_threads=nbofproc-avload;
  return suggested_num_threads;
}
Пример #16
0
int main(int argc, char *argv[])
{
    long                brandID = 0;
    Boolean             AddUsers = false;
    Boolean             SetSavers = false;
    Boolean             isBMGroupMember, isBPGroupMember;
    Boolean             saverIsSet = false;
    passwd              *pw;
    uid_t               saved_uid;
    group               grpBOINC_master, *grpBOINC_masterPtr;
    group               grpBOINC_project, *grpBOINC_projectPtr;
    char                bmBuf[32768];
    char                bpBuf[32768];
    char                loginName[256];
    short               index, i;
    FILE                *f;
    int                 flag;
    char                *p;
    char                s[1024], buf[1024];
    OSStatus            err;
    
    brandID = GetBrandID();

#ifndef _DEBUG
    if (getuid() != 0) {
        printf("This program must be run as root\n");
        printUsage(brandID);
        return 0;
    }
#endif
    saved_uid = geteuid();

    if (argc < 3) {
        printUsage(brandID);
        return 0;
    }
    
    if (strcmp(argv[1], "-a") == 0) {
        AddUsers = true;
    } else if (strcmp(argv[1], "-s") == 0) {
        AddUsers = true;
        SetSavers = true;
    } else if (strcmp(argv[1], "-r") != 0) {
        printUsage(brandID);
        return 0;
    }

    printf("\n");

    if (!check_branding_arrays(s, sizeof(s))) {
        printf("Branding array has too few entries: %s\n", s);
        return -1;
    }

    loginName[0] = '\0';
    strncpy(loginName, getenv("USER"), sizeof(loginName)-1);
    
    err = getgrnam_r("boinc_master", &grpBOINC_master, bmBuf, sizeof(bmBuf), &grpBOINC_masterPtr);
    if (err) {          // Should never happen unless buffer too small
        puts("getgrnam(\"boinc_master\") failed\n");
        return -1;
    }

    err = getgrnam_r("boinc_project", &grpBOINC_project, bpBuf, sizeof(bpBuf), &grpBOINC_projectPtr);
    if (err) {          // Should never happen unless buffer too small
        puts("getgrnam(\"boinc_project\") failed\n");
        return -1;
    }

    for (index=2; index<argc; index++) {
        // getpwnam works with either the full / login name (pw->pw_gecos) 
        // or the short / Posix name (pw->pw_name)
        pw = getpwnam(argv[index]);
        if ((pw == NULL) || (pw->pw_uid < 501)) {
            printf("User %s not found.\n\n", argv[index]);
            continue;
        }

        flag = 0;
        sprintf(s, "dscl . -read \"/Users/%s\" NFSHomeDirectory", pw->pw_name);    
        f = popen(s, "r");
        if (!f) {
            flag = 1;
            } else {
            while (PersistentFGets(buf, sizeof(buf), f)) {
                p = strrchr(buf, ' ');
                if (p) {
                    if (strstr(p, "/var/empty") != NULL) {
                        flag = 1;
                        break;
                    }
                }
            }
            pclose(f);
        }

        if (flag) {
            sprintf(s, "dscl . -read \"/Users/%s\" UserShell", pw->pw_name);    
            f = popen(s, "r");
            if (!f) {
                flag |= 2;
            } else {
                while (PersistentFGets(buf, sizeof(buf), f)) {
                    p = strrchr(buf, ' ');
                    if (p) {
                        if (strstr(p, "/usr/bin/false") != NULL) {
                            flag |= 2;
                            break;
                        }
                    }
                }
                pclose(f);
            }
        }
    
        if (flag == 3) { // if (Home Directory == "/var/empty") && (UserShell == "/usr/bin/false")
            printf("%s is not a valid user name.\n\n", argv[index]);
            continue;
        }

        printf("%s user %s (/Users/%s)\n", AddUsers? "Adding" : "Removing", pw->pw_gecos, pw->pw_name);

        isBMGroupMember = false;
        i = 0;
        while ((p = grpBOINC_master.gr_mem[i]) != NULL) {  // Step through all users in group boinc_master
            if (strcmp(p, pw->pw_name) == 0) {      // Only the short / Posix names are in the list
                // User is a member of group boinc_master
                isBMGroupMember = true;
                break;
            }
            ++i;
        }

        isBPGroupMember = false;
        i = 0;
        while ((p = grpBOINC_project.gr_mem[i]) != NULL) {  // Step through all users in group boinc_project
            if (strcmp(p, pw->pw_name) == 0) {      // Only the short / Posix names are in the list
                // User is a member of group boinc_master
                isBPGroupMember = true;
                break;
            }
            ++i;
        }

        if ((!isBMGroupMember) && AddUsers) {
            sprintf(s, "dscl . -merge /groups/boinc_master GroupMembership %s", pw->pw_name);
            callPosixSpawn(s);
        }
        
        if ((!isBPGroupMember) && AddUsers) {
            sprintf(s, "dscl . -merge /groups/boinc_project GroupMembership %s", pw->pw_name);
            callPosixSpawn(s);
        }
        
        if (isBMGroupMember && (!AddUsers)) {
            sprintf(s, "dscl . -delete /Groups/boinc_master GroupMembership %s", pw->pw_name);
            callPosixSpawn(s);
        }

        if (isBPGroupMember && (!AddUsers)) {
            sprintf(s, "dscl . -delete /Groups/boinc_project GroupMembership %s", pw->pw_name);
            callPosixSpawn(s);
        }

        if (!AddUsers) {
            // Delete per-user BOINC Manager and screensaver files
            sprintf(s, "rm -fR \"/Users/%s/Library/Application Support/BOINC\"", pw->pw_name);
            callPosixSpawn (s);
        }
    
        // Set or remove login item for this user
        bool useOSASript = false;
        
        if ((compareOSVersionTo(10, 13) < 0)
            || (strcmp(loginName, pw->pw_name) == 0) 
                || (strcmp(loginName, pw->pw_gecos) == 0)) {
            useOSASript = true;
        }
#if USE_OSASCRIPT_FOR_ALL_LOGGED_IN_USERS
        if (! useOSASript) {
            useOSASript = IsUserLoggedIn(pw->pw_name);
        }
#endif
       if (useOSASript) {
            snprintf(s, sizeof(s), "/Users/%s/Library/LaunchAgents/edu.berkeley.boinc.plist", pw->pw_name);
            boinc_delete_file(s);
            SetLoginItemOSAScript(brandID, !AddUsers, pw->pw_name);
        } else {
            SetLoginItemLaunchAgent(brandID, !AddUsers, pw);
        }

        saverIsSet = false;
        err = GetCurrentScreenSaverSelection(pw, s, sizeof(s) -1);
#if VERBOSE
        fprintf(stderr, "Current Screensaver Selection for user %s is: \"%s\"\n", pw->pw_name, s);
#endif
        if (err == noErr) {
            if (!strcmp(s, saverName[brandID])) {
                saverIsSet = true;
            }
        }
        
        if (SetSavers) {
            if (saverIsSet) {
                printf("Screensaver already set to %s for user %s (/Users/%s)\n", saverName[brandID], pw->pw_gecos, pw->pw_name);
            } else {
                printf("Setting screensaver to %s for user %s (/Users/%s)\n", saverName[brandID], pw->pw_gecos, pw->pw_name);
            }
        }
        
        if ((!saverIsSet) && SetSavers) {
            seteuid(pw->pw_uid);    // Temporarily set effective uid to this user
            sprintf(s, "/Library/Screen Savers/%s.saver", saverName[brandID]);
            err = SetScreenSaverSelection(pw, saverName[brandID], s, 0);
#if VERBOSE
            fprintf(stderr, "SetScreenSaverSelection for user %s (uid %d) to \"%s\" returned error %d\n", pw->pw_name, geteuid(), saverName[brandID], err);
#endif
            seteuid(saved_uid);     // Set effective uid back to privileged user
            // This seems to work also:
            // sprintf(buf, "su -l \"%s\" -c 'defaults -currentHost write com.apple.screensaver moduleDict -dict moduleName \"%s\" path \"%s\ type 0'", pw->pw_name, saverName[brandID], s);
            // callPosixSpawn(s);
        }
        
        if (saverIsSet && (!AddUsers)) {
            printf("Setting screensaver to Flurry for user %s (/Users/%s)\n", pw->pw_gecos, pw->pw_name);
            seteuid(pw->pw_uid);    // Temporarily set effective uid to this user
            err = SetScreenSaverSelection(pw, "Flurry", "/System/Library/Screen Savers/Flurry.saver", 0);
#if VERBOSE
            fprintf(stderr, "SetScreenSaverSelection for user %s (%d) to Flurry returned error %d\n", pw->pw_name, geteuid(), err);
#endif
            seteuid(saved_uid);     // Set effective uid back to privileged user
        }

        seteuid(saved_uid);                         // Set effective uid back to privileged user
        
        printf("\n");
    }

    printf("WARNING: Changes may require a system restart to take effect.\n");
    
    return 0;
}
Пример #17
0
/* Main function */
int main ( int argc, char** argv)
{

  /* Default settings for serial connection */
  char *port = "/dev/ttyUSB0";
  int baud = 57600;

  /* Serial read buffer */
  int bytes;
  unsigned char buff[32];

  /* Parse arguments */
  int c;
  while ((c = getopt (argc, argv, "a:p:b:h")) != -1) {
    switch (c)
    {
      case 'a':
        ac_id = atoi(optarg);
        break;
      case 'p':
        port = optarg;
        break;
      case 'b':
        baud = atoi(optarg);
        break;
      case 'h':
      default:
        printf("usage: sdlogger_download [options]\n"
               "  options:\n"
               "    -a \tAircraft ID\n"
               "    -p \tPort (default: /dev/ttyUSB0).\n"
               "    -b \tBaudrate (default: 57600).\n"
               "    -h \tHelp, shows this message.\n");
        exit(0);
    }
  }

  /* Obtain sd2log directory */
  char *pprz_home;
  pprz_home = getenv( "PAPARAZZI_HOME" );
  strcat(sd2log, pprz_home);
  strcat(sd2log, "/sw/logalizer/sd2log temp.tlm");

  /* Get the setting ID with a python script */
  /* TODO: would be nicer to have a C xml parser */
  FILE *in = NULL;
  //strcat(pycommand, pprz_home);
  //strcat(pycommand, "/sw/logalizer/sdlogger_get_setting_id.py %u sdlogger_spi.command");
  char new_command[256];
  strcat(pycommand, "python sdlogger_get_setting_id.py %u sdlogger_spi.command");
  sprintf(new_command, pycommand, ac_id);
  strcpy(pycommand, new_command);

  char returnvalue[128];
  in = popen(pycommand, "r");
  fgets(returnvalue, 128, in);
  setting = atoi(returnvalue);
  pclose(in);
  if (setting == 0) {
    printf("Aborting: %s\n", returnvalue);
    exit(0);
  }

  /* Enable Ctrl+C */
  signal(SIGINT, intHandler);

  /* Open serial port */
  printf("Opening port %s with baudrate B%i\n", port, baud);
  if(serial_init(port, baud) < 0){
    return -1;
  }

  /* Keep polling for logger */
  printf("Searching for logger..");
  time_t counter = time(0);
  time_t timeout = 1; // every second
  while (keep_running && searching) {
    if (time(0) - counter >= timeout) {
      printf(".");
      fflush(stdout);
      write_command(255);
      global_state = WaitingForIndexRequestConfirmation;
      counter = time(0);
    }
    else {
      bytes = read(fd, (unsigned char*) buff, 32);
      parse_bytes(buff, bytes);
      usleep(5000);
    }
  }

  char command[128];
  strcpy(command, "help");
  /* Show available commands */
  printf("\n");
  process_command(command);


  while (keep_running) {
    if (need_input) {
      need_input = false;
      /* Test user input */
      printf("Command> ");
      fgets (command, 128, stdin);
      process_command(command);
    }
    else {
      bytes = read(fd, (unsigned char*) buff, 32);
      parse_bytes(buff, bytes);
    }
  }

  printf("Closing app\n");

  /* Close serial port */
  close_port();

  return 0;
}
  // メイン処理
  void run(const std::string& url, const std::string& name) {
    // 接続およびエラーイベントのリスナを設定する
    client.set_close_listener(std::bind(&SampleClient::on_close, this));
    client.set_fail_listener(std::bind(&SampleClient::on_fail, this));
    client.set_open_listener(std::bind(&SampleClient::on_open, this));
    
    // 接続要求を出す
    client.connect(url);
    { // 別スレッドで動く接続処理が終わるまで待つ
      std::unique_lock<std::mutex> lock(sio_mutex);
      if (!is_connected) {
	sio_cond.wait(sio_mutex);
      }
    }
    
    // "run"コマンドのリスナを登録する
    socket = client.socket();
    socket->on("run", std::bind(&SampleClient::on_run, this, std::placeholders::_1));

    {
      sio::message::ptr send_data(sio::object_message::create());
      std::map<std::string, sio::message::ptr>& map = send_data->get_map();
  
      // objectのメンバ、typeとnameを設定する
      map.insert(std::make_pair("type", sio::string_message::create("native")));
      map.insert(std::make_pair("name", sio::string_message::create(name)));

      // joinコマンドをサーバに送る
      socket->emit("join", send_data);
    }

    while(true) {
      // イベントキューが空の場合、キューが補充されるまで待つ
      std::unique_lock<std::mutex> lock(sio_mutex);
      while (sio_queue.empty()) {
	sio_cond.wait(lock);
      }

      // イベントキューから登録されたデータを取り出す
      sio::message::ptr recv_data(sio_queue.front());
      std::stringstream output;
      char buf[1024];
      
      FILE* fp = nullptr;
      // objectのcommandメンバの値を取得する
      std::string command = recv_data->get_map().at("command")->get_string();
      std::cout << "run:" << command << std::endl;
      // commandを実行し、実行結果を文字列として取得する
      if ((fp = popen(command.c_str(), "r")) != nullptr) {
	while (!feof(fp)) {
	  size_t len = fread(buf, 1, sizeof(buf), fp);
	  output << std::string(buf, len);
	}

      } else {
	// エラーを検出した場合はエラーメッセージを取得する
	output << strerror(errno);
      }
      
      pclose(fp);
      
      sio::message::ptr send_data(sio::object_message::create());
      std::map<std::string, sio::message::ptr>& map = send_data->get_map();

      // コマンドの実行結果をobjectのoutputに設定する
      map.insert(std::make_pair("output", sio::string_message::create(output.str())));
      
      // sio::messageをサーバに送る
      socket->emit("reply", send_data);
      
      // 処理が終わったイベントをキューから取り除く
      sio_queue.pop();
    }
  }
Пример #19
0
void *main_bluetooth(void *arg) {
    int i, err, sock, dev_id = -1;
    int num_rsp = 0, max_rsp = 5, flags = 0, length = 4;  /* [1.28 *<length>]seconds [1.28*4 = 5.12] seconds */
    char addr[19] = {0};
    char cmd[100], cmd1[50];
    char name[248] = {0}, bt_mac[19] = "00:00:00:00:00:00";
    uuid_t uuid = {0};
    int application_id = (int) *(int *) arg;
    char uuid_str[50];
    FILE *fd = NULL;
    if (application_id == 2) {
        printf("\nOpen application: Android Locomate Messaging\n");
        strcpy(uuid_str, "66841278-c3d1-11df-ab31-001de000a901");
    }
    else if (application_id == 3) {
        printf("\nOpen application: Spat Andriod Application\n");
        strcpy(uuid_str, "66841278-c3d1-11df-ab31-001de000a903");
    }
    else if (application_id == 4) {
        printf("\nOpen application: Bluetooth CAN application\n");
        strcpy(uuid_str, "00001101-0000-1000-8000-00805F9B34FB");
        fd = popen("cat /var/can.conf | grep BTCAN_MAC= | cut -d '=' -f 2", "r");
        if (fd != NULL) {
            fscanf(fd, "%s", bt_mac);
            pclose(fd);
            printf("Mac from conf file: %s\n", bt_mac);
        }
    }
    else {
        printf("\nOpen application: Locomate Safety Application\n");
        strcpy(uuid_str, "66841278-c3d1-11df-ab31-001de000a902");
    }
    uint32_t range = 0x0000ffff;
    sdp_list_t *response_list = NULL, *search_list, *attrid_list;
    int status;
    int responses;
    int retries = 0;
    struct sockaddr_rc loc_addr = {0};
    signal(SIGINT, (void *) sig_int);

    /* find the bluetooth device is available or not */
    sprintf(cmd, "/usr/local/bin/hciconfig hci0 up");
    system(cmd);
    for (retries = 0; retries < 5; retries++) {
        dev_id = hci_get_route(NULL);
        if (dev_id < 0) {
            perror("No Bluetooth Adapter Available\n");
            sprintf(cmd, "/usr/local/bin/hciconfig hci0 down");
            system(cmd);
            sprintf(cmd1, "/usr/local/bin/hciconfig hci0 up");
            system(cmd1);
            printf("\nretry getting adapter : %d\n", retries);
        }
        else
            break;
    }
    if (retries == 5) {
        Btooth_forward = -1;
        return NULL;
    }

    for (retries = 0; retries < 5; retries++) { //check for the socket
        sock = hci_open_dev(dev_id);
        if (sock < 0) {
            perror("HCI device open failed");
            retries++;
            printf("\nretries sock : %d\n", retries);
        }
        else
            break;
    }
    if (retries == 5) {
        Btooth_forward = -2;
        return NULL;
    }

    for (retries = 0; retries < 5; retries++) { //check uuid is correct or not
        if (!str2uuid(uuid_str, &uuid)) {
            perror("Invalid UUID");
            retries++;
            printf("\nretries str2 uuid : %d\n", retries);
        }
        else
            break;
    }
    if (retries == 5) {
        Btooth_forward = -3;
        return NULL;
    }

    //printf("\nBluetooth Adapter Found \n");
    info = (inquiry_info *) malloc(MAX_RSP * sizeof(inquiry_info));

    while (1) { // loop to check and establish connection with other device

        while (connection_established == FALSE) {
            bzero(info, (MAX_RSP * sizeof(inquiry_info)));

            num_rsp = hci_inquiry(dev_id, length, max_rsp, NULL, &info,
                                  flags); // inquire for how many devices are available
            if (num_rsp < 0) {
                perror("Inquiry failed");
                sched_yield();
                sleep(1);
                continue;
            }
            printf("Inquiry devices found : %d\n", num_rsp);

            loco_channel = -1;
            for (i = 0; i < num_rsp; i++) {
                sdp_session_t *session;
                ba2str(&(info + i)->bdaddr, addr);
                printf("\nFound Mac: %s ", addr);
                if (application_id == 4 && strcmp("00:00:00:00:00:00", bt_mac)) // check for appid and mac_id
                if (strcasecmp(addr, bt_mac))
                    continue;
                memset(name, 0, sizeof(name));

                if (hci_read_remote_name(sock, &(info + i)->bdaddr, sizeof(name), name, 8000) < 0) //get devices by name
                    strcpy(name, "[unknown]");


                printf("Found : %s name : [[ %s ]]\n", addr, name);
                // connect to the SDP server running on the remote machine
                session = NULL;
                retries = 0;
                while (!session) {
                    session = sdp_connect(BDADDR_ANY, &(info + i)->bdaddr, 0);
                    if (session) break;
                    if (errno != 0) {
                        fprintf(stderr, "sdp_connect failed error no %d : %s \n", errno, strerror(errno));
                    }
                    if ((retries < 2) && ((errno == EALREADY))) {
                        retries++;
                        fprintf(stderr, "Retry sdp_connect %d\t", retries);
                        sched_yield();
                        usleep(300000);//300 ms
                        continue; //continue till 3 times
                    }
                    break;
                } /* while(!session) */
                if (session == NULL) {
                    if (i < (num_rsp - 1))
                        printf("Trying next device -> %d\n", i + 2);
                    continue;
                }

                search_list = NULL;
                attrid_list = NULL;
                response_list = NULL;

                search_list = sdp_list_append(NULL, &uuid); //append list of uuids
                attrid_list = sdp_list_append(NULL, &range); // append list of attributes
                err = 0;
                err = sdp_service_search_attr_req(session, search_list, SDP_ATTR_REQ_RANGE, attrid_list,
                                                  &response_list); //search for attributes from list
                sdp_list_t *r = response_list;
                responses = 0;


                // go through each of the service records
                for (; r; r = r->next) {
                    responses++;
                    sdp_record_t *rec = (sdp_record_t *) r->data;
                    sdp_list_t *proto_list;

                    // get a list of the protocol sequences
                    if (sdp_get_access_protos(rec, &proto_list) == 0) {
                        sdp_list_t *p = proto_list;

                        // go through each protocol sequence
                        for (; p; p = p->next) {
                            sdp_list_t *pds = (sdp_list_t *) p->data;

                            // go through each protocol list of the protocol sequence
                            for (; pds; pds = pds->next) {

                                // check the protocol attributes
                                sdp_data_t *d = (sdp_data_t *) pds->data;
                                int proto = 0;
                                for (; d; d = d->next) {
                                    switch (d->dtd) {
                                        case SDP_UUID16:
                                        case SDP_UUID32:
                                        case SDP_UUID128:
                                            proto = sdp_uuid_to_proto(&d->val.uuid);
                                            break;
                                        case SDP_UINT8:
                                            if (proto == RFCOMM_UUID) {
                                                printf("rfcomm channel: %d\n", d->val.int8);
                                                loco_channel = d->val.int8;
                                            }
                                            break;
                                    } /* switch(t->dtd) */
                                } /* for( ; d; d = d->next) */
                            } /* for( ; pds ; pds = pds->next) */
                            sdp_list_free((sdp_list_t *) p->data, 0);
                        } /* for( ; p; p = p->next) */
                        sdp_list_free(proto_list, 0);
                    } /* if(sdp_get_access_protos(rec, &proto_list)) */
                    sdp_record_free(rec);
                    if (loco_channel > 0) {
                        break;
                    }
                } /* for (; r; r = r->next) */


                sdp_list_free(response_list, 0);
                sdp_list_free(search_list, 0);
                sdp_list_free(attrid_list, 0);
                printf("No of services= %d on device %d \n", responses, i + 1);
                if (loco_channel > 0) {
                    // printf("Found Locomate Safety Application on device: name [%s], sending message now\n",name);
                    btooth_socket = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
                    loc_addr.rc_family = AF_BLUETOOTH;
                    loc_addr.rc_channel = loco_channel;
                    loc_addr.rc_bdaddr = (info + i)->bdaddr;
                    status = connect(btooth_socket, (struct sockaddr *) &loc_addr, sizeof(loc_addr));
                    if (status < 0) {
                        perror("\nuh oh: Btooth socket not created\n");
                        Btooth_forward = -5;
                    }
                    else {
                        sdp_close(session);
                        Btooth_forward = 1;
                        connection_established = TRUE;
                        break;
                    }
                }
                sdp_close(session);
            } /* for (i = 0; i < num_rsp; i++) */
            if (connection_established == FALSE) {
                printf("Scanning again\n");
                //sprintf(cmd, "/usr/local/bin/hciconfig hci0 down");
                //system(cmd);
                sprintf(cmd1, "/usr/local/bin/hciconfig hci0 up");
                system(cmd1);
                sched_yield();
                sleep(1);
            }
            else {
                printf("***Connection established***\n");
            }
        } /* while(connection_established == ...) */
        sched_yield();
        sleep(3); // wait for 3seconds, before next check
    }

}
Пример #20
0
main(){
	int sockfd;// to create socket
	char message[MSGSIZE];
	int nsockfd;
	int clilen;
	char message1[MAXSIZE+1];
	int n;
	int rec = 0;
	struct sockaddr_in server_address, client_address;

	if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	  { perror("Server: socket() error\n");
	    exit(1); };

	/* Get Server's IP address */
	FILE *file;
	char returnData[64];
	char *token;
	char a[1000];	
	file = popen("/sbin/ifconfig eth0", "r");
	while (fgets(returnData, 64, file) != NULL)
	{strcat(a, returnData);}

	
	token = strtok(a, " ");
	token = strtok(NULL, " ");
	token = strtok(NULL, " ");
	token = strtok(NULL, " ");
	token = strtok(NULL, " ");
	token = strtok(NULL, " ");
	token = strtok(NULL, " ");
	token = strtok(NULL, " addr:");

	/* print the IP address token */
	printf("Server IP address: %s\n", token);

	bzero((char *) &server_address, sizeof(server_address));
	server_address.sin_family = AF_INET;
	server_address.sin_addr.s_addr = inet_addr(token);
	server_address.sin_port = htons(SERV_TCP_PORT);

	pclose(file);

	if(bind(sockfd, (struct sockaddr *) &server_address, sizeof(server_address)) < 0)
	perror("Server: bind() error\n");
	printf("\nConnection.......  .......... [bind]\n");

	char *buf; 
	buf=(char *)malloc(10*sizeof(char)); 
	buf=getlogin(); 
	
	char path[30]; 
	strcpy(path, "/home/");
	strcat(path, buf); 
	strcat(path, "/FILE_OF_SERVER"); 
	 
	struct stat s; 
	if(stat(path, &s) == -1){ 
	mkdir(path, 0700); }

	listen(sockfd, 5);
	int p[2];
	if(pipe(p) == -1)
	{
		perror("Fail to create pipe");
		exit(1);
	} 

	for(;;)

{
	 clilen = sizeof(client_address);
	 nsockfd = accept(sockfd, (struct sockaddr *)&client_address, &clilen);

	
	char *clientaddress = inet_ntoa(client_address.sin_addr);
	char *individual_address; 
	write(p[1], &clientaddress, sizeof(clientaddress));
	

	if(fork() == 0){
	  close(sockfd);
	  strcpy(message1,"** Hello, welcome to the server. ** \n\nPress\n1.Send File\t2.Download File\n3.Create Directory\t4.Delete Directory(include sub directory)\n[type /q to quit] : ");
	  send(nsockfd, message1, MAXSIZE, 0);


	if(nsockfd > 0)
		
	  read(p[0],&individual_address,sizeof(individual_address));
	  printf("\nClient %s connected now.\n", individual_address);
	  
	
	  
	do { n=recv(nsockfd, message, MSGSIZE, 0);
	 
	      if(!strcmp(message, "1"))
	{	
		bzero( message, sizeof(message));
		strcat(message,"[List of files in Server Directory]\nPlease choose a file from above the list to download:\n\n");
		
		DIR *dir;
		struct dirent *ent;

		char directoryName[30];
		strcpy(directoryName, "/home/");
    		strcat(directoryName, buf); 
    		strcat(directoryName, "/FILE_OF_SERVER/");
	
		if ((dir = opendir (directoryName)) != NULL) {
		
			
 			while ((ent = readdir (dir)) != NULL) {

			strcat(message, ent->d_name);
			strcat(message, "\n");
 			}
 		 closedir (dir);
		send(nsockfd, message, MAXSIZE, 0);
		 
		}
		
  		
 		else  { perror ("Directory not exist.");
  		return EXIT_FAILURE;
		}

	bool exist = true; 

	

        
do{ 	bzero( message, sizeof(message));
	recv(nsockfd, message, MAXSIZE, 0);

	char filename[30];
    	strcpy(filename, "/home/"); 
    	strcat(filename, buf); 
    	strcat(filename, "/FILE_OF_SERVER/");
    	strcat(filename, message);
    
	
	FILE *file = fopen(filename, "r");
	if(file==NULL)
        {
            strcpy(message," NO such file in server.Please key in the correct filename with extension.");
	    send(nsockfd, message, MAXSIZE, 0);  
	    exist = false; 
	   
        }  
	
	if(exist == true )
	{
	 bzero( message, sizeof(message));
	 int nread = fread(message,1,256,file);
	 send(nsockfd, message, nread, 0);
	}

	bzero( message, sizeof(message));
	strcpy(message,"Sucessfully Downloaded. [/q to quit]");

	}while(exist == false);}
	
	
	
	 if(!strcmp(message, "2"))
	
		
{	 bzero( message, sizeof(message));
	 recv(nsockfd, message, MAXSIZE, 0);

	char filename[30];
	strcpy(filename, "/home/"); 
	strcat(filename, buf); 
	strcat(filename, "/FILE_OF_SERVER/");
	strcat(filename, message);
		

	FILE *file;
   	 file = fopen(filename, "ab"); 
	bzero( message, sizeof(message));
	rec = recv(nsockfd, message, MAXSIZE, 0);
	fwrite(message,1,rec,file);
	fclose(file);

	bzero( message, sizeof(message));
	strcat(message,"Congratulation you have sent the file you want. [/q to quit]");
	}
	
	 
	if(!strcmp(message, "3"))
	{
		bzero( message, sizeof(message));
		strcat(message,"Congratulation you have maked the directory. [/q to quit]");
	}

	if(!strcmp(message, "4"))
	{
		bzero( message, sizeof(message));
		strcat(message,"Congratulation you have deleted directory. [/q to quit]");
	}

	if(n==0)
	{
	close(nsockfd);
	break;
	}
	message[n]=0;
	 send(nsockfd, message, MAXSIZE, 0);
	}while(strcmp(message1, "/q"));

	printf("\nClient %s disconnected now.\n", individual_address);
	exit(0);
	}
	close(nsockfd);
	}
	
	return 0;
}
Пример #21
0
void
rad2mgf(		/* convert a Radiance file to MGF */
	char	*inp
)
{
	char  buf[512];
	char  mod[128], typ[32], id[128], alias[128];
	FUNARGS	fa;
	register FILE	*fp;
	register int	c;

	if (inp == NULL) {
		inp = "standard input";
		fp = stdin;
	} else if (inp[0] == '!') {
		if ((fp = popen(inp+1, "r")) == NULL) {
			fputs(inp, stderr);
			fputs(": cannot execute\n", stderr);
			exit(1);
		}
	} else if ((fp = fopen(inp, "r")) == NULL) {
		fputs(inp, stderr);
		fputs(": cannot open\n", stderr);
		exit(1);
	}
	printf("# Begin conversion from: %s\n", inp);
	while ((c = getc(fp)) != EOF)
		switch (c) {
		case ' ':		/* white space */
		case '\t':
		case '\n':
		case '\r':
		case '\f':
			break;
		case '#':		/* comment */
			if (fgets(buf, sizeof(buf), fp) != NULL)
				printf("# %s", buf);
			break;
		case '!':		/* inline command */
			ungetc(c, fp);
			fgetline(buf, sizeof(buf), fp);
			rad2mgf(buf);
			break;
		default:		/* Radiance primitive */
			ungetc(c, fp);
			if (fgetword(mod, sizeof(mod), fp) == NULL ||
					fgetword(typ, sizeof(typ), fp) == NULL ||
					fgetword(id, sizeof(id), fp) == NULL) {
				fputs(inp, stderr);
				fputs(": unexpected EOF\n", stderr);
				exit(1);
			}
			unspace(mod);
			unspace(id);
			if (!strcmp(typ, "alias")) {
				strcpy(alias, "EOF");
				fgetword(alias, sizeof(alias), fp);
				unspace(alias);
				newmat(id, alias);
			} else {
				if (!readfargs(&fa, fp)) {
					fprintf(stderr,
				"%s: bad argument syntax for %s \"%s\"\n",
							inp, typ, id);
					exit(1);
				}
				cvtprim(inp, mod, typ, id, &fa);
				freefargs(&fa);
			}
			break;
		}
	printf("# End conversion from: %s\n", inp);
	if (inp[0] == '!')
		pclose(fp);
	else
		fclose(fp);
}
Пример #22
0
log::log::~log(){
	if(fp)
		fclose(fp);
	if(tp)
		pclose(tp);
}
Пример #23
0
bool find_sql_updates()
{
    printf("+ finding new sql updates on HEAD\n");
    // add all updates from HEAD
    snprintf(cmd, MAX_CMD, "git show HEAD:%s", sql_update_dir);
    if ((cmd_pipe = popen(cmd, "r")) == NULL)
        return false;

    // skip first two lines
    if (!fgets(buffer, MAX_BUF, cmd_pipe)) { pclose(cmd_pipe); return false; }
    if (!fgets(buffer, MAX_BUF, cmd_pipe)) { pclose(cmd_pipe); return false; }

    sql_update_info info;

    while (fgets(buffer, MAX_BUF, cmd_pipe))
    {
        buffer[strlen(buffer) - 1] = '\0';
        if (!get_sql_update_info(buffer, info)) continue;

        if (info.db_idx == NUM_DATABASES)
        {
            if (info.rev > 0) printf("WARNING: incorrect database name for sql update %s\n", buffer);
            continue;
        }

        new_sql_updates.insert(buffer);
    }

    pclose(cmd_pipe);

    // Add last milestone's file information
    last_sql_rev[0] = 11785;
    last_sql_nr[0] = 2;
    sscanf("11785_02_characters_instance", "%s", last_sql_update[0]);
    last_sql_rev[2] = 10008;
    last_sql_nr[2] = 1;
    sscanf("10008_01_realmd_realmd_db_version", "%s", last_sql_update[2]);

    // remove updates from the last commit also found on origin
    snprintf(cmd, MAX_CMD, "git show %s:%s", origin_hash, sql_update_dir);
    if ((cmd_pipe = popen(cmd, "r")) == NULL)
        return false;

    // skip first two lines
    if (!fgets(buffer, MAX_BUF, cmd_pipe)) { pclose(cmd_pipe); return false; }
    if (!fgets(buffer, MAX_BUF, cmd_pipe)) { pclose(cmd_pipe); return false; }

    while (fgets(buffer, MAX_BUF, cmd_pipe))
    {
        buffer[strlen(buffer) - 1] = '\0';
        if (!get_sql_update_info(buffer, info)) continue;

        // find the old update with the highest rev for each database
        // (will be the required version for the new update)
        std::set<std::string>::iterator itr = new_sql_updates.find(buffer);
        if (itr != new_sql_updates.end())
        {
            if (info.rev > 0 && (info.rev > last_sql_rev[info.db_idx] ||
                                 (info.rev == last_sql_rev[info.db_idx] && info.nr > last_sql_nr[info.db_idx])))
            {
                last_sql_rev[info.db_idx] = info.rev;
                last_sql_nr[info.db_idx] = info.nr;
                if (db_sql_rev_parent[info.db_idx])
                    snprintf(last_sql_update[info.db_idx], MAX_PATH, "%s_%0*d_%s%s%s", info.parentRev, 2, info.nr, info.db, info.has_table ? "_" : "", info.table);
                else
                    sscanf(buffer, "%[^.]", last_sql_update[info.db_idx]);
            }
            new_sql_updates.erase(itr);
        }
    }

    pclose(cmd_pipe);

    if (!new_sql_updates.empty())
    {
        for (std::set<std::string>::iterator itr = new_sql_updates.begin(); itr != new_sql_updates.end(); ++itr)
            printf("%s\n", itr->c_str());
    }
    else
        printf("WARNING: no new sql updates found.\n");

    return true;
}
Пример #24
0
/* Integrate the RS spectra with the detector response */
double rs_det( double *ex, int *nrs, float *emin, float *de )
{
        int	i,icgs,dlength,j,loc,numt,spec_bins,k,locl,loch,abs_n;
	double	*spec,lambda_cgs,lambda_det,lambda_s,integral,val,cnts2cgs;
	float	*elo,*ehi,*area,spec_emin,spec_de,spec_scale,bandmin,
	  bandmax,emid,te,*spec_e,abs_e[260],abs_sigma[260],y2abs[260],
	  *absorption,sigma,NH;
        char  dirname[300],infile1[300],infile2[300],command[300];
	char  trash[200],junk[200];
	FILE *inp,*pip;
	void  spline(),splint();

	/* H column density [10^20 cm^-2] */
	NH = 0.0;
	icgs = 0;  /* [icgs = 1 (CGS: erg s^-1 cm^-2], 0 [cnts s^-1] */

	*spec = *ex;
	spec_bins = *nrs;
	spec_emin = *emin;
	spec_de = *de;
	
        strcpy(dirname,"/dworkin/home/daisuke/Raymond/EffArea/");
	strcat(infile1,dirname);
	strcat(infile2,dirname);
	strcat(infile1,"chandra_acis-s-bi_0.3-7.0keV.eff");
	strcat(infile2,"cross_sections.dat");
	
	/* calculate length of detector area file */
	sprintf(command,"wc %s",infile1);
	pip=popen(command,"r");
	fscanf(pip,"%d",&dlength);
	dlength--;
	pclose(pip);
	elo=(float *)calloc(dlength,sizeof(float));
	ehi=(float *)calloc(dlength,sizeof(float));
	area=(float *)calloc(dlength,sizeof(float));
	/* read in detector effective area */
	inp=fopen(infile1,"r");
	fgets(trash,200,inp);
	sscanf(trash,"%s %f %f",&junk,&bandmin,&bandmax);
	printf("# %s:  Band is %5.2f:%5.2f with %d energy channels\n",
	  infile1,bandmin,bandmax,dlength);
	for (i=0;i<dlength;i++) 
	  fscanf(inp,"%f %f %f",elo+i,ehi+i,area+i);
	fclose(inp);

	/* read in the galactic absorption cross sections */
	inp=fopen(infile2,"r");
	abs_n=0;while(fgets(trash,200,inp)!=NULL) {
	  if (strncmp(trash,"#",1)) {
	    sscanf(trash,"%f %f",abs_e+abs_n,abs_sigma+abs_n);
	    abs_n++;
	  }
	}
	fclose(inp);
	/* spline this for future use */
	spline(abs_e-1,abs_sigma-1,abs_n,0.0,0.0,y2abs-1);

	/* cycle through rs-spectra, calculating lambdas */
	
	/* exit if spectra don't extend beyond range of detector sensitivity */
	if (bandmin<spec_emin || bandmax>spec_emin+spec_de*spec_bins) {
	  printf("  Detector energy range larger than R-S spectra range\n");
	  exit(0);
	}

	spec=(double *)calloc(spec_bins,sizeof(double));
	spec_e=(float *)calloc(spec_bins,sizeof(float));
	absorption=(float *)calloc(spec_bins,sizeof(float));

	for (j=0;j<spec_bins;j++) {
	  spec_e[j]=spec_emin+(float)j*spec_de;
	  /* calculate the absorption cross section at this energy */
	  if (spec_e[j]<abs_e[0]) sigma=abs_sigma[0];
	  else { 
	    if (spec_e[j]>abs_e[abs_n-1]) sigma=abs_sigma[abs_n-1];
	    else splint(abs_e-1,abs_sigma-1,y2abs-1,abs_n,spec_e[j],&sigma);
	  }
	  absorption[j]=exp(-1.0*sigma*NH);
	  /* RS spectrum is modified by the galactic absorption */ 
	  spec[j]*=absorption[j];
	}

	/* calculate lambda in detector units */
	lambda_det=0.0;
	for (j=0;j<dlength;j++) {
	  /* integrate over spectral emissivity from elo[] to ehi[] */
	  locl=(int)((elo[j]-spec_emin)/spec_de);
	  loch=(int)((ehi[j]-spec_emin)/spec_de);
	  /* detector bin lies within single R-S bin */
	  if (locl==loch) integral=area[j]*(ehi[j]-elo[j])*spec[locl];
	  else {/* detector bin extends over more than one R-S bin */
	    /* take care of the first partial bin */
	    integral=(spec_de-(elo[j]-spec_e[locl]))*spec[locl];
	    /* add all the enclosed bins */
	    for (k=locl+1;k<loch;k++) integral+=spec_de*spec[k];
	    /* take care of the last partial bin */
	    integral+=(ehi[j]-spec_e[loch])*spec[loch];
	    /* now scale by the area of this detector bin */
	    integral*=area[j];
	  }
	  /* convert from cgs to counts */
	  emid=0.5*(elo[j]+ehi[j]);
	  val=integral/(emid*KEV_2_ERGS);
	  lambda_det+=val;
	}
	/* now calculate theoretical lambda in cgs units */
	loc=(bandmin-spec_emin)/spec_de;
	/* initialize using value from first partial bin */
	lambda_cgs=(spec_de-(bandmin-spec_e[loc]))*spec[loc];
	/* add contribution from all the full bins */
	for (j=loc+1;j<spec_bins;j++) {
	  if (bandmax>spec_e[j+1])
	    lambda_cgs+=spec_de*spec[j];
	  else break;
	}
	/* add contribution from last partial bin */
	lambda_cgs+=(bandmax-spec_e[j])*spec[j];
	/* calculate conversion from observed count rate to cgs flux */
	if (lambda_det>0.0) cnts2cgs=lambda_cgs/lambda_det;
	else cnts2cgs=0.0;

	if (icgs ==1) return(lambda_cgs); 
	if (icgs ==0) return(lambda_det);
}
Пример #25
0
	// In this method, we will execute the nslookup command and return back
	// four pieces of information in a map ash shown below.
	// "Name Server Name" => "Name of the name server"
	// "Name Server Address" => "IP address of the name server"
	// "Client Machine Name" => "Fully qualified name of the client machine"
	// "Client Machine Address" => "IP address of the client machine"
	unordered_map<string, string> NameServerLookup::getNSLookupResults(string const & nodeName) {
		FILE *fpipe;
		string nsLookupCommand = (string)"nslookup " + nodeName;
		char line[256];
		unordered_map <string, string> result;
		string replyLineKey1 = "Name Server Name";
		string replyLineKey2 = "Name Server Address";
		string replyLineKey3 = "Client Machine Name";
		string replyLineKey4 = "Client Machine Address";

		if (!(fpipe = (FILE*)popen(nsLookupCommand.c_str(),"r"))) {
			// If fpipe is NULL
			// Mark the errors in the map.
			result[replyLineKey1] = "Pipe failure";
			result[replyLineKey2] = "Pipe failure";
			result[replyLineKey3] = "Pipe failure";
			result[replyLineKey4] = "Pipe failure";
			return (result);
		} // End of if (!(fpipe = (FILE*)popen(command,"r")))

		int32_t cnt = 1;

		while (fgets( line, sizeof line, fpipe)) {
			// nslookup result looks like this.
			// Server:         10.4.24.230
			// Address:        10.4.24.230#53
			//
			// Name:   a0217b10e1.hny.distillery.ibm.com
			// Address: 10.4.40.210
			//
			// Let us parse only the last token in every line as that is what we want.
			//
			std::string resultStr = string(line);
			// construct a stream from the string
			std::stringstream strStream(resultStr);

			// use stream iterators to copy the stream to the vector as whitespace separated strings
			std::istream_iterator<std::string> it(strStream);
			std::istream_iterator<std::string> end;
			std::vector<std::string> results(it, end);
			// cout << "Vector size = " << results.size() << endl;

			// Let us now get the last token in the vector.
			std::string lastToken = "";

			if (results.size() > 0) {
				lastToken = results.at(results.size() - 1);
			} // End of if (results.size() > 0)

			switch (cnt++) {
				case 1:
					result[replyLineKey1] = lastToken;
					break;

				case 2:
					result[replyLineKey2] = lastToken;
					break;

				case 3:
					// This must be an empty line in the nslookup result.
					break;

				case 4:
					result[replyLineKey3] = lastToken;
					break;

				case 5:
					result[replyLineKey4] = lastToken;
					break;
			} // End of switch (cnt++)

			// If we already processed 5 lines, we have
			// collected everything we need from the result.
			if (cnt > 5) {
				// Break from the while loop.
				break;
			} // End of if (cnt > 5)

			// printf("%s", line);
		} // End of while (fgets( line, sizeof line, fpipe))

		pclose (fpipe);
		return (result);
	} // End of method getNSLookupResults(string & nodeName).
/*
 * Using the current debconf settings for a mirror, figure out which suite
 * to use from the mirror and set mirror/suite.
 *
 * This is accomplished by downloading the Release file from the mirror.
 * Suite selection tries each suite in turn, and stops at the first one that
 * seems usable.
 *
 * If no Release file is found, returns false. That probably means the
 * mirror is broken or unreachable.
 */
int find_suite (void) {
	char *command;
	FILE *f = NULL;
	char *hostname, *directory;
	int nbr_suites = sizeof(suites)/SUITE_LENGTH;
	int i;
	int ret = 0;
	char buf[SUITE_LENGTH];

	if (show_progress) {
		debconf_progress_start(debconf, 0, 1,
				       DEBCONF_BASE "checking_title");
		debconf_progress_info(debconf,
				      DEBCONF_BASE "checking_download");
	}

	hostname = add_protocol("hostname");
	debconf_get(debconf, hostname);
	free(hostname);
	hostname = strdup(debconf->value);
	directory = add_protocol("directory");
	debconf_get(debconf, directory);
	free(directory);
	directory = strdup(debconf->value);

	/* Try each suite in turn until one is found that works. */
	for (i=0; i <= nbr_suites && ! ret; i++) {
		char *suite;

		if (i == 0) {
			/* First check for a preseeded suite. */
			debconf_get(debconf, DEBCONF_BASE "suite");
			if (strlen(debconf->value) > 0) {
				suite = strdup(debconf->value);
			}
			else {
				/* Read this file to find the default suite
				 * to use. */
				f = fopen("/etc/default-release", "r");
				if (f != NULL) {
					if (fgets(buf, SUITE_LENGTH - 1, f)) {
						if (buf[strlen(buf) - 1] == '\n')
							buf[strlen(buf) - 1] = '\0';
						suite = strdup(buf);
						fclose(f);
					}
					else {
						fclose(f);
						continue;
					}
				}
				else {
					continue;
				}
			}
			
		}
		else {
			suite = strdup(suites[i - 1]);
		}

		asprintf(&command, "wget -q %s://%s%s/dists/%s/Release -O - | grep ^Suite: | cut -d' ' -f 2",
			 protocol, hostname, directory, suite);
		di_log(DI_LOG_LEVEL_DEBUG, "command: %s", command);
		f = popen(command, "r");
		free(command);

		if (f != NULL) {
			if (fgets(buf, SUITE_LENGTH - 1, f)) {
				if (buf[strlen(buf) - 1] == '\n')
					buf[strlen(buf) - 1] = '\0';
				debconf_set(debconf, DEBCONF_BASE "suite", buf);
				ret = 1;
			}
		}

		pclose(f);
		free(suite);
	}

	free(hostname);
	free(directory);

	if (show_progress) {
		debconf_progress_step(debconf, 1);
		debconf_progress_stop(debconf);
	}

	return ret;
}
Пример #27
0
string * FASTA_Parser::getSequence() {
	string line;
	
	
	if (sequence != 0) {
		cerr << "error: sequence has already been read via getSequence()" << endl;
		exit(1);
	}
	
	sequence = new string();
	
	if (expected_sequence_length > 0) {
		sequence->reserve(expected_sequence_length);
	}
	
	//cerr << "getSequence" << endl;
	
	//cout <<"line: "<< line << endl;
	while (true) {
		std::getline(*rna_stream, line);
		if (rna_stream->fail()) {
			break;
		}
		//cout << "fail: " << rna_stream->fail() << endl;
		
		//cerr << "y:" << line << endl;
		if (line.length() == 0) {
			continue;
		}
		
		if (line[0] == '#' ) {
			continue;
		}
		
		if (line[0] == '>' ) {
			
			//this->description_line = getFASTADescription(line);
			if (getOnlyIdentfier) {
				this->description_line = getFASTADescription(line);
			} else {
				this->description_line = line;
			}
			have_read_descr = false;
			sequence->reserve(sequence->length());
			return sequence;
		} else {
			int lastpos = line.length()-1;
			if (line[lastpos] == '\n') {
				line.erase(lastpos); // remove trailing newline
			}
			//sequence->append("@");
			//cout << "append" << endl;
			sequence->append(line);
		}
	}
	
	//file_closed = true;
	if (fp != 0) {
		pclose(fp);
		fp = 0;
	}
	sequence->reserve(sequence->length());
	return sequence;
	
}
Пример #28
0
int pg_getfname ( char *subset, char *fname, char *descr )
/************************************************************************
 * pg_getfname								*
 *									*
 * This function retrieves the name of a plot file from the plot node	*
 * based upon the product index table.					*
 *									*
 * int pg_getfname  ( subset, fname, descr )				*
 *									*
 * Input parameters:							*
 *	*subset		char 	Subset to retrieve			*
 *									*
 * Output parameters:							*
 *	*fname		char 	Name of file for this subset		*
 *	*descr		char	ASCII descriptor of that subset		*
 *	pg_getfname	int	Return value:				*
 *				-1	Failure				*
 *				 0	Success				*
 **									*
 * Log:									*
 * E. Wehner/EAi	 5/96	Created				 	*
 * T. Piper/GSC		10/98	Prolog update				*
 ***********************************************************************/
{

    FILE *pfp;
    char cmd[120];
    char cmd_in[120];
    char file_name[20];
    char *s;
    int i;

    sprintf(cmd, "rsh %s@%s %s %s | cut -c7-", 
				PLOT_USERNAME, PLOT_NODE, PLOT_INDEXCMD,
				subset);

    if ( (pfp = popen(cmd, "r")) != 0)
    {
        fgets(cmd_in, sizeof(cmd_in), pfp);
 
        pclose (pfp);

        /* get the name of the file by looking at the first 14 bytes */
        strncpy(file_name, cmd_in, 16);
        file_name[16] = '\0';

        s = &file_name[0];
        /* remove the left padding from the filenam */
        while ( (*s <= ' ') && (s < &file_name[19]) ) s++;

        if ( ( s[0] < ' ') || (s[0] > 'z') )
        {
            return -1;
        }
        sprintf(fname, "%s/%s", getenv("FAX_TEMP"), s);

        /* remove cr if it is there */
        for (i=0;i<(int)strlen(fname); i++)
            if (fname[i] <= ' ') fname[i] = '\0';


        strncpy(descr, &cmd_in[15], 100);

    }
    else
        return -1;

    return 0;
  
}
Пример #29
0
//client connection
void respond(int n)
{
  char *result = (char *) malloc(sizeof(char) * 10000);// result return to client
  char *pure_path = (char *) malloc(sizeof(char) * 10000);// get path 
  char *buf = (char *) malloc(sizeof(char) * 10000);
  char *cmd1 = (char *) malloc(sizeof(char) * 1000);// command for 'ls -l'
  char *cmd2 = (char *) malloc(sizeof(char) * 1000);// command for 'cat '
  char *param = "/?param=";
  char *pos;
  char c;
  int index;
  FILE *file;// use pipeline
  struct stat s;// use to know if the path is a file or a directory

  char mesg[99999], *reqline[3], data_to_send[BYTES], path[99999], html[999];
  int rcvd, fd, bytes_read;

  memset( (void*)mesg, (int)'\0', 99999 );

  //rcvd=recv(clients[n], mesg, 99999, 0);
  rcvd=read(clients[n], mesg, 99999);

  if (rcvd<0)    // receive error
    fprintf(stderr,("recv() error\n"));
  else if (rcvd==0)    // receive socket closed
    fprintf(stderr,"Client disconnected upexpectedly.\n");
  else    // message received
    {
      printf("%s", mesg);
      reqline[0] = strtok (mesg, " \t\n");
      if ( strncmp(reqline[0], "GET\0", 4)==0 )
	{
	  reqline[1] = strtok (NULL, " \t");
	  reqline[2] = strtok (NULL, " \t\n");
	  if ( strncmp( reqline[2], "HTTP/1.0", 8)!=0 && strncmp( reqline[2], "HTTP/1.1", 8)!=0 )
	    {
	      write(clients[n], "HTTP/1.0 400 Bad Request\n", 25);
	    }
	  else
	    {
	      pos = strstr(reqline[1], param) + 8; //get 1st position when meet '/?param=', +8 means pass through until the real path. Ex: /home/ubuntu/syspro
	      
	      index = 0;
	      // get path(not include '/?param='), terminate when meet ' '
	      while ((c = *pos) != NULL) {
		pure_path[index++] = c;
		pos++;
	      }
	      pure_path[index] = '\n';
	     	      if (stat(pure_path, &s) == 0) {
		if (s.st_mode & S_IFDIR) {
		  printf("path is a directory\n");
		  strcat(cmd1, "ls -l ");//initialize comd1 as 'ls -l'
		  strcat(cmd1, pure_path);//now, it becomes, for example, "ls -l /home/ubuntu/"
		  file = popen(cmd1, "r");//execute command and open a pipeline
		  while (fgets(buf, 10000, file))
		    strcat(result, buf);//read and add content of the pipeline into result
		  pclose(file);
		  printf("%s\n", result);
		} else if (s.st_mode & S_IFREG) {
		  printf("path is a file\n");
		  strcat(cmd2, "cat ");//initialize comd2 as 'cat '
		  strcat(cmd2, pure_path);//now, it becomes, for example, "cat /home/ubuntu/syspro/f13.c"
		  file = popen(cmd2, "r");//excute command and open a pipeline
		  while (fgets(buf, 10000, file))
		    strcat(result, buf);//read and add content of the pipeline into result
		  pclose(file);
		  printf("%s\n", result);
		} else {
		  printf("something else!\n");
	        }
	      } else {
		strcat(result, "Error!\n");
		printf("wtf! Error!!\n");
	      }
	      write(clients[n], result,strlen(result));
	    }
	}
    }
  //Closing SOCKET
  shutdown (clients[n], SHUT_RDWR);      //All further send and recieve operations are DISABLED...
  close(clients[n]);
  clients[n]=-1;
  exit(0);
}
Пример #30
0
int exec_str(struct sip_msg *msg, str* cmd, char *param, int param_len) {

	struct action act;
	int cmd_len;
	FILE *pipe;
	char *cmd_line;
	int ret;
	char uri_line[MAX_URI_SIZE+1];
	int uri_cnt;
	int uri_len;
	int exit_status;

	/* pessimist: assume error by default */
	ret=-1;

	cmd_len=cmd->len+param_len+2;
	cmd_line=pkg_malloc(cmd_len);
	if (cmd_line==0) {
		ret=ser_error=E_OUT_OF_MEM;
		LOG(L_ERR, "ERROR: exec_str: no mem for command\n");
		goto error00;
	}

	/* 'command parameter \0' */
	memcpy(cmd_line, cmd->s, cmd->len); cmd_line[cmd->len]=' ';
	memcpy(cmd_line+cmd->len+1, param, param_len);cmd_line[cmd->len+param_len+1]=0;

	pipe=popen( cmd_line, "r" );
	if (pipe==NULL) {
		LOG(L_ERR, "ERROR: exec_str: cannot open pipe: %s\n",
			cmd_line);
		ser_error=E_EXEC;
		goto error01;
	}

	/* read now line by line */
	uri_cnt=0;
	while( fgets(uri_line, MAX_URI_SIZE, pipe)!=NULL){
		uri_len=strlen(uri_line);
		/* trim from right */
		while(uri_len && (uri_line[uri_len-1]=='\r'
				|| uri_line[uri_len-1]=='\n'
				|| uri_line[uri_len-1]=='\t'
				|| uri_line[uri_len-1]==' ' )) {
			DBG("exec_str: rtrim\n");
			uri_len--;
		}
		/* skip empty line */
		if (uri_len==0) continue;
		/* ZT */
		uri_line[uri_len]=0;
		if (uri_cnt==0) {
			memset(&act, 0, sizeof(act));
			act.type = SET_URI_T;
			act.val[0].type = STRING_ST;
			act.val[0].u.string = uri_line;
			if (do_action(&act, msg)<0) {
				LOG(L_ERR,"ERROR:exec_str : SET_URI_T action failed\n");
				ser_error=E_OUT_OF_MEM;
				goto error02;
			}
		} else {
			if (append_branch(msg, uri_line, uri_len, 0, 0, Q_UNSPECIFIED, 0)==-1) {
				LOG(L_ERR, "ERROR: exec_str: append_branch failed;"
					" too many or too long URIs?\n");
				goto error02;
			}
		}
		uri_cnt++;
	}
	if (uri_cnt==0) {
		LOG(L_ERR, "ERROR:exec_str: no uri from %s\n", cmd_line );
		goto error02;
	}
	/* success */
	ret=1;

error02:
	if (ferror(pipe)) {
		LOG(L_ERR, "ERROR: exec_str: error in pipe: %s\n",
			strerror(errno));
		ser_error=E_EXEC;
		ret=-1;
	}
	exit_status=pclose(pipe);
	if (WIFEXITED(exit_status)) { /* exited properly .... */
		/* return false if script exited with non-zero status */
		if (WEXITSTATUS(exit_status)!=0) ret=-1;
	} else { /* exited erroneously */
		LOG(L_ERR, "ERROR: exec_str: cmd %.*s failed. "
			"exit_status=%d, errno=%d: %s\n",
			cmd->len, ZSW(cmd->s), exit_status, errno, strerror(errno) );
		ret=-1;
	}
error01:
	pkg_free(cmd_line);
error00:
	return ret;
}