Esempio n. 1
0
int analyze(char *trace,char *config,char *output,char *log)
{
	unsigned int i,chunk_num;
	unsigned int size_in_window=0,req_in_window=0;
	long double time_in_window=0;
	double i_non_access=0,i_inactive=0,i_seq_intensive=0,i_seq_less_intensive=0,i_random_intensive=0,i_random_less_intensive=0;

	struct pool_info *pool;
	pool=(struct pool_info *)malloc(sizeof(struct pool_info));
	alloc_assert(pool,"pool");
	memset(pool,0,sizeof(struct pool_info));

	load_parameters(pool,config);
	initialize(pool,trace,output,log);

#ifdef _NETAPP_TRACE_
	chunk_num=get_range_netapp(pool);
	fgets(pool->buffer,SIZE_BUFFER,pool->file_trace);	//read the first line out
	while(get_request_netapp(pool)!=FAILURE)
#else
	chunk_num=get_range_msr(pool);
	while(get_request_msr(pool)!=FAILURE)
#endif
	{
		if(pool->window_type==WINDOW_DATA)
		{
			seq_detection(pool);	//Sequential IO Detection
			update_statistics(pool);

			//update window info
			size_in_window+=pool->req->size;
			req_in_window++;
			if(req_in_window==1)
				pool->window_time_start=pool->req->time;
			pool->window_time_end=pool->req->time;
			
			//THE CURRENT WINDOW IS FULL
			if((size_in_window>=pool->window_size*2048)||((feof(pool->file_trace)!=0)&&(size_in_window>0)))
			{
				flush_stream(pool);	//Flush information in POOL->STREAMS into each Chunks
				/*Pattern Detection*/
				time_in_window=(long double)(pool->window_time_end-pool->window_time_start)/(long double)1000000000;
				pool->window_time[pool->window_sum]=time_in_window;
				pool->chunk_access[pool->window_sum]=pool->chunk_win;

				for(i=pool->chunk_min;i<=pool->chunk_max;i++)
				{
					if(pool->chunk[i].req_sum_all==0)//no access
					{
						/*No Access*/
						if(pool->record_all[i].accessed!=0)
						{
							i_non_access++;
						}
						pool->chunk[i].pattern=PATTERN_NON_ACCESS;
					}
					else if(pool->chunk[i].req_sum_all<pool->threshold_inactive)//inactive
					{
						/*Inactive*/
						i_inactive++;
						if(((long double)pool->chunk[i].req_sum_read/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
						{
							/*Inactive Read*/
							pool->chunk[i].pattern=PATTERN_INACTIVE_R;
						}
						else if(((long double)pool->chunk[i].req_sum_write/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
						{
							/*Inactive Write*/
							pool->chunk[i].pattern=PATTERN_INACTIVE_W;
						}
						else{
							/*Inactive Hybrid*/
							pool->chunk[i].pattern=PATTERN_INACTIVE_H;
						}
					}
					else if((pool->chunk[i].seq_size_all/pool->chunk[i].req_size_all)>=pool->threshold_cbr &&
						((long double)pool->chunk[i].seq_sum_all/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_car)
					{
						/*SEQUENTIAL*/
						i_seq_intensive++;
						/*Sequential Intensive*/
						if(pool->chunk[i].req_sum_all>=(req_in_window/pool->chunk_win)*pool->threshold_intensive)
						{
							if(((long double)pool->chunk[i].req_sum_read/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
							{
								/*Sequential Intensive Read*/
								pool->chunk[i].pattern=PATTERN_SEQ_INTENSIVE_R;
							}
							else if(((long double)pool->chunk[i].req_sum_write/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
							{
								/*Sequential Intensive Write*/
								pool->chunk[i].pattern=PATTERN_SEQ_INTENSIVE_W;
							}
							else
							{
								/*Sequential Intensive Hybrid*/
								pool->chunk[i].pattern=PATTERN_SEQ_INTENSIVE_H;
							}
						}
						else{
							i_seq_less_intensive++;
							if(((long double)pool->chunk[i].req_sum_read/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
							{
								/*Sequential Less Intensive Read*/
								pool->chunk[i].pattern=PATTERN_SEQ_LESS_INTENSIVE_R;
							}
							else if(((long double)pool->chunk[i].req_sum_write/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
							{
								/*Sequential Less Intensive Write*/
								pool->chunk[i].pattern=PATTERN_SEQ_LESS_INTENSIVE_W;
							}
							else
							{
								/*Sequential Less Intensive Hybrid*/
								pool->chunk[i].pattern=PATTERN_SEQ_LESS_INTENSIVE_H;
							}
						}
					}
					else{
						/*Random*/
						i_random_intensive++;
						if(pool->chunk[i].req_sum_all>=(req_in_window/pool->chunk_win)*pool->threshold_intensive)
						{
							if(((long double)pool->chunk[i].req_sum_read/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
							{
								/*Random Intensive Read*/
								pool->chunk[i].pattern=PATTERN_RANDOM_INTENSIVE_R;
							}
							else if(((long double)pool->chunk[i].req_sum_write/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
							{
								/*Random Intensive Write*/
								pool->chunk[i].pattern=PATTERN_RANDOM_INTENSIVE_W;
							}
							else
							{
								/*Random Intensive Hybrid*/
								pool->chunk[i].pattern=PATTERN_RANDOM_INTENSIVE_H;
							}
						}
						else{
							i_random_less_intensive++;
							if(((long double)pool->chunk[i].req_sum_read/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
							{
								/*Random Less Intensive Read*/
								pool->chunk[i].pattern=PATTERN_RANDOM_LESS_INTENSIVE_R;
							}
							else if(((long double)pool->chunk[i].req_sum_write/(long double)pool->chunk[i].req_sum_all)>=pool->threshold_rw)
							{
								/*Random Less Intensive Write*/
								pool->chunk[i].pattern=PATTERN_RANDOM_LESS_INTENSIVE_W;
							}
							else
							{
								/*Random Less Intensive Hybrid*/
								pool->chunk[i].pattern=PATTERN_RANDOM_LESS_INTENSIVE_H;
							}
						}
					}
					//Only record limited information (the first SIZE_ARRY windows)
					if(pool->window_sum<SIZE_ARRAY)
					{
						pool->chunk[i].history_pattern[pool->window_sum]=pool->chunk[i].pattern;

						pool->pattern_non_access[pool->window_sum]=i_non_access/(double)pool->chunk_all;
						pool->pattern_inactive[pool->window_sum]=i_inactive/(double)pool->chunk_all;
						pool->pattern_seq_intensive[pool->window_sum]=i_seq_intensive/(double)pool->chunk_all;
						pool->pattern_seq_less_intensive[pool->window_sum]=i_seq_less_intensive/(double)pool->chunk_all;
						pool->pattern_random_intensive[pool->window_sum]=i_random_intensive/(double)pool->chunk_all;
						pool->pattern_random_less_intensive[pool->window_sum]=i_random_less_intensive/(double)pool->chunk_all;
					}
					
					print_log(pool,i);	//print info of each chunk in this window to log file.
					/*Initialize the statistics in each chunk*/
					pool->chunk[i].req_sum_all=0;
					pool->chunk[i].req_sum_read=0;
					pool->chunk[i].req_sum_write=0;
					pool->chunk[i].req_size_all=0;
					pool->chunk[i].req_size_read=0;
					pool->chunk[i].req_size_write=0;

					pool->chunk[i].seq_sum_all=0;
					pool->chunk[i].seq_sum_read=0;
					pool->chunk[i].seq_sum_write=0;
					pool->chunk[i].seq_stream_all=0;
					pool->chunk[i].seq_stream_read=0;
					pool->chunk[i].seq_stream_write=0;
					pool->chunk[i].seq_size_all=0;
					pool->chunk[i].seq_size_read=0;
					pool->chunk[i].seq_size_write=0;
				}//for
				
				/*Update the pool info*/
				pool->window_sum++;
				if(pool->window_sum%20==0)
					printf("------pool->window_sum=%d---------\n",pool->window_sum);
				pool->window_time_start=0;
				pool->window_time_end=0;
				
				/*Start a new window*/
				size_in_window=0;
				req_in_window=0;
				time_in_window=0;
				
				i_non_access=0;
				i_inactive=0;
				i_seq_intensive=0;
				i_seq_less_intensive=0;
				i_random_intensive=0;
				i_random_less_intensive=0;

				//accessed chunks in each window
				memset(pool->record_win,0,sizeof(struct record_info)*pool->chunk_sum);
				printf("pool->chunk_win=%d\n",pool->chunk_win);
				pool->chunk_win=0;
			}//if
		}//if
	}//while

	print_statistics(pool);

	fclose(pool->file_trace);
	fclose(pool->file_output);
	fclose(pool->file_log);
	
	free(pool->chunk);
	free(pool->map);
	free(pool->req);
	free(pool);

	return SUCCESS;
}
Esempio n. 2
0
static void pcap_handle(u_char *user, const struct pcap_pkthdr *h, const u_char *buf)
{
	static unsigned failCount = 0;
	pthread_t thread_lan;

#ifndef NO_ARP
	if (buf[0x0c]==0x88 && buf[0x0d]==0x8e) {
#endif
		if (memcmp(destMAC, buf+6, 6)!=0 && startMode>2)	/* 服务器MAC地址不符 */
			return;
		capBuf = buf;
		if (buf[0x0F]==0x00 && buf[0x12]==0x01 && buf[0x16]==0x01) {	/* 验证用户名 */
			if (startMode < 3) {
				memcpy(destMAC, buf+6, 6);
				print_log(_("** 认证服务器MAC: %s\n"), formatHex(destMAC, 6));
				startMode += 3;	/* 标记认证服务器MAC为已获取,可以锁定 */
			}
			if (proxyMode == 0) {
				if (startMode==3 && memcmp(buf+0x17, "User name", 9)==0)	/* 塞尔 */
					startMode = 5;
				switchState(ID_IDENTITY);
			} else {
				if (proxyClientRequested == 1) {
					print_log(_(">> 服务器已请求用户名\n"));
					proxy_send_to_lan(buf, h->len);
				} else {
					print_log(_("!! 在代理认证完成后收到用户名请求,将重启认证!\n"));
					switchState(ID_WAITCLIENT);
				}
			}
		}
		else if (buf[0x0F]==0x00 && buf[0x12]==0x01 && buf[0x16]==0x04)	{ /* 验证密码 */
			if (proxyMode == 0) {
				switchState(ID_CHALLENGE);
			} else {
				if (proxyClientRequested == 1) {
					print_log(_(">> 服务器已请求密码\n"));
					proxy_send_to_lan(buf, h->len);
				} else {
					print_log(_("!! 在代理认证完成后收到密码请求,将重启认证!\n"));
					switchState(ID_WAITCLIENT);
				}
			}
		}
		else if (buf[0x0F]==0x00 && buf[0x12]==0x03) {	/* 认证成功 */
			print_log(_(">> 认证成功!\n"));
			failCount = 0;
			proxySuccessCount++;
			if (proxyMode != 0) {
				proxy_send_to_lan(buf, h->len);
				if (proxySuccessCount >= proxyRequireSuccessCount) {
					pcap_breakloop(hPcapLan);
					proxyClientRequested = 0;
					proxySuccessCount = 0;
					memcpy(lastSuccessClientMAC, clientMAC, 6); // 备份本次认证成功的客户端MAC,用于通知掉线
					proxy_clear_client_mac(); // 重设MAC地址,以备下次使用不同客户端认证用
					print_log(_(">> 已关闭LAN监听线程\n"));
				}
			}
			if (!(startMode%3 == 2)) {
				getEchoKey(buf);
			}
			showRuijieMsg(buf, h->caplen);
			if (dhcpMode==1 || dhcpMode==2)	/* 二次认证第一次或者认证后 */
				switchState(ID_DHCP);
			else if (startMode%3 == 2)
				switchState(ID_WAITECHO);
			else
				switchState(ID_ECHO);
		}
		else if (buf[0x0F]==0x00 && buf[0x12]==0x01 && buf[0x16]==0x02)	/* 显示赛尔提示信息 */
			showCernetMsg(buf);
		else if (buf[0x0F] == 0x05)	/* (赛尔)响应在线 */
			switchState(ID_ECHO);
		else if (buf[0x0F]==0x00 && buf[0x12]==0x04) {  /* 认证失败或被踢下线 */
			if (state==ID_WAITECHO || state==ID_ECHO) {
				if (proxyMode == 0) {
					print_log(_(">> 认证掉线!\n"));
					showRuijieMsg(buf, h->caplen);
					if (restartOnLogOff) {
						print_log(_(">> 正在重新认证...\n"));
						switchState(ID_START);					
					} else {
						exit(1);
					}
				} else {
					pthread_create(&thread_lan, NULL, lan_thread, 0);
					print_log(_(">> 认证掉线,已发回客户端并重新启用对LAN的监听\n"));
					showRuijieMsg(buf, h->caplen);
					// clientMAC已经在成功时被清除了,所以使用lastSuccessClientMAC发送,发完清除
					memmove(clientMAC, lastSuccessClientMAC, 6);
					proxy_send_to_lan(buf, h->len);
					proxy_clear_client_mac();
					switchState(ID_WAITCLIENT);
				}
			}
			else if (buf[0x1b]!=0 || startMode%3==2) {
				print_log(_(">> 认证失败!\n"));
				showRuijieMsg(buf, h->caplen);
				if (maxFail && ++failCount>=maxFail) {
					print_log(_(">> 连续认证失败%u次,退出认证。\n"), maxFail);
					exit(EXIT_SUCCESS);
				}
				restart();
			} else {
				if (proxyMode == 0)
					switchState(ID_START);
				else
					switchState(ID_WAITCLIENT);
			}
		}
#ifndef NO_ARP
	} else if (gateMAC[0]!=0xFE && buf[0x0c]==0x08 && buf[0x0d]==0x06) {
		if (*(u_int32_t *)(buf+0x1c) == gateway) {
			char str[50];
			if (gateMAC[0] == 0xFF) {
				memcpy(gateMAC, buf+0x16, 6);
				print_log(_("** 网关MAC:\t%s\n"), formatHex(gateMAC, 6));
				sprintf(str, "arp -s %s %s", formatIP(gateway), formatHex(gateMAC, 6));
				system(str);
			} else if (buf[0x15]==0x02 && memcmp(&rip, buf+0x26, 4)==0
				&& memcmp(gateMAC, buf+0x16, 6)!=0) {
				print_log(_("** ARP欺骗:\t%s\n"), formatHex(buf+0x16, 6));
#ifndef NO_NOTIFY
				if (showNotify) {
					sprintf(str, _("欺骗源: %s"), formatHex(buf+0x16, 6));
					if (show_notify(_("MentoHUST - ARP提示"), str, 1000*showNotify) < 0)
						showNotify = 0;
				}
#endif
			}
		}
	}
#endif
}
Esempio n. 3
0
File: utils.c Progetto: BwRy/tgcd
void print_log(int dlevel, const char *format_str, ...)
{
#else
void print_log(va_alist)
va_dcl
{
 	int  dlevel;
	const char *format_str;
#endif
#ifdef DEBUG
	char log_msg[256];
	char time_buf[64];
	time_t now;
	va_list	ap;
	char err_str[64];
	struct timeval tv;

	//if (!logfile) return;

	if (dlevel<=0)
		return;

	err_str[0]='\0';

#ifdef __STDC__
	va_start(ap, format_str);
#else
	va_start(ap);
	dlevel = va_arg(ap,int);
	format_str = va_arg(ap,char *);
#endif
	if (dlevel <= log_level) {
		//now = time(NULL);
		gettimeofday(&tv, NULL);
		now = tv.tv_sec;
		strftime(time_buf, 64, "%Y/%m/%d %T", localtime(&now));
		vsnprintf(log_msg, 256, format_str, ap);

		if (errno && log_level>5) {
			sprintf(err_str, " errno=%d(%s)", errno, strerror(errno)); 
			errno=0;
		}

		if (logfile) {
			fprintf(logfile, "%s.%ld:: %s%s\n", time_buf, tv.tv_usec, log_msg, err_str);
			fflush(logfile);
		}

		if (!is_it_daemon) 
			fprintf(stderr, "%s.%ld:: %s%s\n", time_buf, tv.tv_usec, log_msg, err_str);
	}
	va_end(ap);

#endif
}
/*------------------------------------------------------------------
  Writes a log message to the log file, and on the stderr if not daemon
------------------------------------------------------------------*/
#ifdef __STDC__
void print_log_msg(int dlevel, const char *func, const char *format_str, ...)
{
#else
void print_log_msg(va_alist)
va_dcl
{
 	int  dlevel;
	char *func;
	const char *format_str;
#endif
#ifdef DEBUG
	char tmp_msg[256];
	char log_msg[256];
	va_list	ap;

	//if (!logfile) return;

	if (dlevel<=0)
		return;

#ifdef __STDC__
	va_start(ap, format_str);
#else
	va_start(ap);
	dlevel = va_arg(ap,int);
	format_str = va_arg(ap,char *);
#endif
	vsnprintf(tmp_msg, 256, format_str, ap);
	if (func) {
		snprintf(log_msg, 256, "%s: %s", func, tmp_msg);
		print_log(dlevel, log_msg);
	} else 
		print_log(dlevel, tmp_msg);

	va_end(ap);

#endif
}

/*-----------------------------------------------------------------------------
    To prevent zombie child processes.
------------------------------------------------------------------------------*/
RETSIGTYPE sig_cld()
{
       //signal(SIGCLD, sig_cld);
       //while (waitpid((pid_t)-1, (int *) NULL, WNOHANG) > 0);

	while (wait3((int *)NULL, WNOHANG, (struct rusage *)NULL) > 0);
}

/*---------------------------------------------------------------------------
   true if the machine is big endian
---------------------------------------------------------------------------*/
int big_endian(void)
{
	int x = 2;
	char *s;
	s = (char *)&x;

	return(s[0] == 0);
}
Esempio n. 4
0
int main(int argc, char **argv)
{
    const char *lua_init = "init.lua";
    // parse command line
    while(1)
    {
        static struct option long_options[] =
        {
            {"help", no_argument, 0, '?'},
            {"quiet", no_argument, 0, 'q'},
            {0, 0, 0, 0}
        };

        int c = getopt_long(argc, argv, "?qi:", long_options, NULL);
        if(c == -1)
            break;
        switch(c)
        {
            case -1:
                break;
            case 'q':
                g_quiet = true;
                break;
            case '?':
                usage();
                break;
            case 'i':
                lua_init = optarg;
                break;
            default:
                abort();
        }
    }

    // load register descriptions
    std::vector< soc_t > socs;
    for(int i = optind; i < argc; i++)
        if(!soc_desc_parse_xml(argv[i], socs))
        {
            printf("Cannot load description '%s'\n", argv[i]);
            return 2;
        }

    // create usb context
    libusb_context *ctx;
    libusb_init(&ctx);
    libusb_set_debug(ctx, 3);

    // look for device
    if(!g_quiet)
        printf("Looking for device %#04x:%#04x...\n", HWSTUB_USB_VID, HWSTUB_USB_PID);

    libusb_device_handle *handle = libusb_open_device_with_vid_pid(ctx,
        HWSTUB_USB_VID, HWSTUB_USB_PID);
    if(handle == NULL)
    {
        printf("No device found\n");
        return 1;
    }

    // admin stuff
    libusb_device *mydev = libusb_get_device(handle);
    if(!g_quiet)
    {
        printf("device found at %d:%d\n",
            libusb_get_bus_number(mydev),
            libusb_get_device_address(mydev));
    }
    g_hwdev = hwstub_open(handle);
    if(g_hwdev == NULL)
    {
        printf("Cannot open device!\n");
        return 1;
    }

    // get hwstub information
    int ret = hwstub_get_desc(g_hwdev, HWSTUB_DT_VERSION, &g_hwdev_ver, sizeof(g_hwdev_ver));
    if(ret != sizeof(g_hwdev_ver))
    {
        printf("Cannot get version!\n");
        goto Lerr;
    }
    if(g_hwdev_ver.bMajor != HWSTUB_VERSION_MAJOR || g_hwdev_ver.bMinor < HWSTUB_VERSION_MINOR)
    {
        printf("Warning: this tool is possibly incompatible with your device:\n");
        printf("Device version: %d.%d.%d\n", g_hwdev_ver.bMajor, g_hwdev_ver.bMinor, g_hwdev_ver.bRevision);
        printf("Host version: %d.%d.%d\n", HWSTUB_VERSION_MAJOR, HWSTUB_VERSION_MINOR, HWSTUB_VERSION_REV);
    }

    // get memory layout information
    ret = hwstub_get_desc(g_hwdev, HWSTUB_DT_LAYOUT, &g_hwdev_layout, sizeof(g_hwdev_layout));
    if(ret != sizeof(g_hwdev_layout))
    {
        printf("Cannot get layout: %d\n", ret);
        goto Lerr;
    }

    // get target
    ret = hwstub_get_desc(g_hwdev, HWSTUB_DT_TARGET, &g_hwdev_target, sizeof(g_hwdev_target));
    if(ret != sizeof(g_hwdev_target))
    {
        printf("Cannot get target: %d\n", ret);
        goto Lerr;
    }

    // get STMP specific information
    if(g_hwdev_target.dID == HWSTUB_TARGET_STMP)
    {
        ret = hwstub_get_desc(g_hwdev, HWSTUB_DT_STMP, &g_hwdev_stmp, sizeof(g_hwdev_stmp));
        if(ret != sizeof(g_hwdev_stmp))
        {
            printf("Cannot get stmp: %d\n", ret);
            goto Lerr;
        }
    }
    /** Init lua */

    // create lua state
    g_lua = luaL_newstate();
    if(g_lua == NULL)
    {
        printf("Cannot create lua state\n");
        return 1;
    }
    // import hwstub
    if(!my_lua_import_hwstub())
        printf("Cannot import hwstub description into Lua context\n");
    // open all standard libraires
    luaL_openlibs(g_lua);
    // import socs
    if(!my_lua_import_soc(socs))
        printf("Cannot import SoC descriptions into Lua context\n");

    if(luaL_dofile(g_lua, lua_init))
        printf("error in init: %s\n", lua_tostring(g_lua, -1));
    lua_pop(g_lua, lua_gettop(g_lua));

    /** start interactive mode */
    if(!g_quiet)
        printf("Starting interactive lua session. Type 'help()' to get some help\n");

    // use readline to provide some history and completion
    rl_bind_key('\t', rl_complete);
    while(!g_exit)
    {
        char *input = readline("> ");
        if(!input)
            break;
        add_history(input);
        // evaluate string
        if(luaL_dostring(g_lua, input))
            printf("error: %s\n", lua_tostring(g_lua, -1));
        // pop everything to start from a clean stack
        lua_pop(g_lua, lua_gettop(g_lua));
        free(input);
    }

    Lerr:
    // display log if handled
    if(!g_quiet)
        printf("Device log:\n");
    print_log(g_hwdev);
    hwstub_release(g_hwdev);
    return 1;
}
int main(int argc, char *argv[])
{
    char ch;
    char str[STR_BUFFSIZE];

    char plom_help_string[] =
        "PLOM ksimplex\n"
        "usage:\n"
        "ksimplex [implementation] [--no_dem_sto] [--no_white_noise] [--no_diff]\n"
        "                          [-s, --DT <float>] [--eps_abs <float>] [--eps_rel <float>]\n"
        "                          [-p, --path <path>] [-i, --id <integer>]\n"
        "                          [-g, --freeze_forcing <float>]\n"
        "                          [--prior] [--transf]\n"
        "                          [-l, --LIKE_MIN <float>] [-S, --size <float>] [-M, --iter <integer>]\n"
	"                          [-q, --quiet] [-P, --pipe]"
        "                          [-h, --help]\n"
        "where implementation is 'sde' (default)\n"
        "options:\n"
	"\n"
        "-q, --quiet          no verbosity\n"
        "-P, --pipe           pipe mode (echo theta.json on stdout)\n"
	"\n"
        "--no_dem_sto       turn off demographic stochasticity (if possible)\n"
        "--no_white_noise       turn off environmental stochasticity (if any)\n"
        "--no_diff         turn off drift (if any)\n"
	"\n"
        "-s, --DT           Initial integration time step\n"
	"--eps_abs          Absolute error for adaptive step-size control\n"
	"--eps_rel          Relative error for adaptive step-size control\n"
        "-g, --freeze_forcing  freeze the metadata to their value at the specified time\n"
	"\n"
        "--prior            to maximize posterior density in natural space\n"
        "--transf           to maximize posterior density in transformed space (if combined with --prior)\n"
        "-p, --path         path where the outputs will be stored\n"
        "-i, --id           general id (unique integer identifier that will be appended to the output files)\n"
        "-l, --LIKE_MIN     particles with likelihood smaller that LIKE_MIN are considered lost\n"
        "-M, --iter         maximum number of iterations\n"
        "-S, --size         simplex size used as a stopping criteria\n"
        "-b, --no_traces    do not write the traces\n"
	"-o, --nb_obs       number of observations to be fitted (for tempering)"
        "--help             print the usage on stdout\n";

    // simplex options
    M = 10;
    CONVERGENCE_STOP_SIMPLEX = 1e-6;

    // general options
    GENERAL_ID =0;
    snprintf(SFR_PATH, STR_BUFFSIZE, "%s", DEFAULT_PATH);
    J=1;
    LIKE_MIN = 1e-17;
    LOG_LIKE_MIN = log(1e-17);
    int nb_obs = -1;
    double freeze_forcing = -1.0;

    // options
    OPTION_PRIOR = 0;
    OPTION_TRANSF = 0;

    double dt = 0.0, eps_abs = PLOM_EPS_ABS, eps_rel = PLOM_EPS_REL;

    enum plom_print print_opt = PLOM_PRINT_BEST;

    enum plom_implementations implementation;
    enum plom_noises_off noises_off = 0;


    static struct option long_options[] = {
        {"help",       no_argument,       0, 'h'},
        {"no_trace",   no_argument,  0, 'b'},

	{"no_dem_sto", no_argument,       0, 'x'},
	{"no_white_noise", no_argument,       0, 'y'},
	{"no_diff",   no_argument,       0, 'z'},


	{"DT",         required_argument, 0, 's'},
	{"eps_abs",    required_argument, 0, 'v'},
	{"eps_rel",    required_argument, 0, 'w'},

	{"freeze_forcing", required_argument, 0, 'g'},

        {"path",       required_argument, 0, 'p'},
        {"id",         required_argument, 0, 'i'},

        {"prior",  no_argument, &OPTION_PRIOR,  1},
        {"transf", no_argument, &OPTION_TRANSF, 1},

        {"LIKE_MIN", required_argument, 0, 'l'},
        {"iter",     required_argument,   0, 'M'},
        {"size",     required_argument,   0, 'S'},
	{"nb_obs", required_argument,  0, 'o'},

	{"quiet",  no_argument,       0, 'q'},
	{"pipe",  no_argument,       0, 'P'},

        {0, 0, 0, 0}
    };

    int option_index = 0;
    while ((ch = getopt_long (argc, argv, "qPhxyzs:v:w:i:l:p:S:M:o:bg:", long_options, &option_index)) != -1) {
        switch (ch) {
        case 0:
            break;

        case 'x':
            noises_off = noises_off | PLOM_NO_DEM_STO;
            break;
        case 'y':
            noises_off = noises_off | PLOM_NO_ENV_STO;
            break;
        case 'z':
            noises_off = noises_off | PLOM_NO_DRIFT;
            break;
        case 's':
            dt = atof(optarg);
            break;
        case 'v':
            eps_abs = atof(optarg);
            break;
        case 'w':
            eps_rel = atof(optarg);
            break;
        case 'h':
            print_log(plom_help_string);
            return 1;
        case 'b':
            print_opt &= ~PLOM_PRINT_BEST;
            break;
        case 'p':
            snprintf(SFR_PATH, STR_BUFFSIZE, "%s", optarg);
            break;
        case 'i':
            GENERAL_ID = atoi(optarg);
            break;
        case 'g':
            freeze_forcing = atof(optarg);
            break;
	case 'o':
	    nb_obs = atoi(optarg);
            break;
        case 'l':
            LIKE_MIN = atof(optarg);
            LOG_LIKE_MIN = log(LIKE_MIN);
            break;
        case 'M':
            M = atoi(optarg);
            break;
        case 'S':
            CONVERGENCE_STOP_SIMPLEX = atof(optarg);
            break;

        case 'q':
	    print_opt |= PLOM_QUIET;
            break;
        case 'P':
	    print_opt |= PLOM_PIPE | PLOM_QUIET;
            break;

        case '?':
            /* getopt_long already printed an error message. */
            return 1;

        default:
            snprintf(str, STR_BUFFSIZE, "Unknown option '-%c'\n", optopt);
            print_err(str);
            return 1;
        }
    }
    argc -= optind;
    argv += optind;

    if(argc == 0) {
	implementation = PLOM_ODE; //with Kalman the SDE uses f_pred of PLOM_ODE (OK will do better)...
    } else {
        if (!strcmp(argv[0], "sde")) {
            implementation = PLOM_ODE;
        } else {
            print_log(plom_help_string);
            return 1;
        }
    }
    plom_unlink_done(SFR_PATH, GENERAL_ID);
    json_t *settings = load_settings(PATH_SETTINGS);

    int64_t time_begin, time_end;
    if (!(print_opt & PLOM_QUIET)) {
	snprintf(str, STR_BUFFSIZE, "Starting plom-ksimplex with the following options: i = %d, LIKE_MIN = %g", GENERAL_ID, LIKE_MIN);
	print_log(str);
	time_begin = s_clock();
    }

    json_t *theta = load_json();
    struct s_kalman *p_kalman = build_kalman(theta, settings, implementation, noises_off, OPTION_PRIOR, dt, eps_abs, eps_rel, freeze_forcing, nb_obs);
    json_decref(settings);

    simplex(p_kalman->p_best, p_kalman->p_data, p_kalman, f_simplex_kalman, CONVERGENCE_STOP_SIMPLEX, M, print_opt);

    if (!(print_opt & PLOM_QUIET)) {
	time_end = s_clock();
	struct s_duration t_exec = time_exec(time_begin, time_end);
	snprintf(str, STR_BUFFSIZE, "Done in:= %dd %dh %dm %gs", t_exec.d, t_exec.h, t_exec.m, t_exec.s);
	print_log(str);
    }

    plom_print_done(theta, p_kalman->p_data, p_kalman->p_best, SFR_PATH, GENERAL_ID, print_opt);

    if (!(print_opt & PLOM_QUIET)) {
	print_log("clean up...");
    }

    json_decref(theta);

    clean_kalman(p_kalman);

    return 0;
}
static int broadcast_Isdb_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
	int rc = 0;
	int addr = 0;

#if defined (CONFIG_ARCH_MSM8992) || defined (CONFIG_ARCH_MSM8994)
    printk("[dtv]broadcast_Isdb_i2c_probe client:0x%lX\n", (UDynamic_32_64)client);
#else
    printk("[dtv]broadcast_Isdb_i2c_probe client:0x%X\n", (UDynamic_32_64)client);
#endif

	if(!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
		print_log(NULL, "need I2C_FUNC_I2C\n");
		return -ENODEV;
	}
    IsdbCtrlInfo.pdev = to_platform_device(&client->dev);

	/* taew00k.kang added for Device Tree Structure 2013-06-04 [start] */
	addr = client->addr; //Slave Addr
	pr_err("[dtv] i2c Slaveaddr [%x] \n", addr);

	IsdbCtrlInfo.pclient = client;
	//i2c_set_clientdata(client, (void*)&IsdbCtrlInfo.pclient);

#ifdef FEATURE_DMB_USE_XO
    IsdbCtrlInfo.xo_clk = clk_get(&IsdbCtrlInfo.pclient->dev, "isdbt_xo");
    if(IS_ERR(IsdbCtrlInfo.xo_clk)){
        rc = PTR_ERR(IsdbCtrlInfo.xo_clk);
        dev_err(&IsdbCtrlInfo.pclient->dev, "[dtv]could not get clock\n");
        return rc;
    }
    /* We enable/disable the clock only to assure it works */
    rc = clk_prepare_enable(IsdbCtrlInfo.xo_clk);
    if(rc) {
        dev_err(&IsdbCtrlInfo.pclient->dev, "[dtv] could not enable clock\n");
        return rc;
    }
    clk_disable_unprepare(IsdbCtrlInfo.xo_clk);
#endif

#ifdef FEATURE_DMB_USE_PINCTRL
    isdbt_pinctrl_init();
#endif

    /* Config GPIOs */
    broadcast_Isdb_config_gpios();

#ifdef FEATURE_DMB_USE_REGULATOR
    broadcast_isdbt_set_regulator(1);
    broadcast_isdbt_set_regulator(0);
#endif

#ifndef _NOT_USE_WAKE_LOCK_
	wake_lock_init(&IsdbCtrlInfo.wake_lock, WAKE_LOCK_SUSPEND,
					dev_name(&client->dev));
#endif

#if defined (CONFIG_ARCH_MSM8992) || defined (CONFIG_ARCH_MSM8994)
    fc8300_power_on();
    tunerbb_drv_fc8300_read_chip_id();
    fc8300_power_off();
#endif

	return rc;
}
static int broadcast_Isdb_i2c_resume(struct i2c_client* client)
{
	int rc = 0;
	print_log(NULL, "[%s]\n", __func__);
	return rc;
}
Esempio n. 8
0
void initGlPrint(int w, int h)
{
    const GLfloat quadVertices[] = {
        0,	0,	0,
        16, 16, 0,
        16,	0,	0,

        16, 16, 0,
        0,	0,	0,
        0,	16,	0
    };

    const GLfloat texCoord[] = {
        0,			0,
        1. / 16,	1. / 16,
        1. / 16,	0,
        1. / 16,	1. / 16,
        0,			0,
        0,			1. / 16
    };


    kmMat4OrthographicProjection(&__glp.opm, 0, w, h, 0, -10, 10);

    GLuint vs, fs;
    vs = create_shader("resources/shaders/glprint.vert", GL_VERTEX_SHADER);
    fs = create_shader("resources/shaders/glprint.frag", GL_FRAGMENT_SHADER);

    __glp.printProg = glCreateProgram();
    glAttachShader(__glp.printProg, vs);
    glAttachShader(__glp.printProg, fs);
    glLinkProgram(__glp.printProg);
    int link_ok;
    glGetProgramiv(__glp.printProg, GL_LINK_STATUS, &link_ok);
    if (!link_ok) {
        printf("glLinkProgram:");
        print_log(__glp.printProg);
        printf("\n");
    }

    __glp.cx_uniform = getShaderLocation(shaderUniform, __glp.printProg, "cx");
    __glp.cy_uniform = getShaderLocation(shaderUniform, __glp.printProg, "cy");
    __glp.opm_uniform =
        getShaderLocation(shaderUniform, __glp.printProg, "opm_uniform");
    __glp.texture_uniform =
        getShaderLocation(shaderUniform, __glp.printProg, "texture_uniform");

    __glp.vert_attrib = getShaderLocation(shaderAttrib, __glp.printProg, "vert_attrib");
    __glp.uv_attrib = getShaderLocation(shaderAttrib, __glp.printProg, "uv_attrib");

    __glp.fonttex = loadPNG("resources/textures/font.png");

    glGenBuffers(1, &__glp.quadvbo);
    glBindBuffer(GL_ARRAY_BUFFER, __glp.quadvbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 3 * 6, quadVertices,
                 GL_STATIC_DRAW);

    glGenBuffers(1, &__glp.texvbo);
    glBindBuffer(GL_ARRAY_BUFFER, __glp.texvbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 2 * 6, texCoord,
                 GL_STATIC_DRAW);

}
Esempio n. 9
0
void initSprite(int w, int h)
{
    const GLfloat quadVertices[] = {
        -.5,	-.5,	0,
        .5,  	 .5,	0,
        .5,	-.5,	0,

        .5,  	 .5,	0,
        -.5,	-.5,	0,
        -.5,	 .5,	0
    };

    const GLfloat texCoord[] = {
        0,		0,
        1.,		1,
        1.,		0,
        1.,		1.,
        0,		0,
        0,		1.
    };


    kmMat4OrthographicProjection(&__spr.opm, 0, w, h, 0, -10, 10); // support layers ?

    GLuint vs, fs;
    vs = create_shader("resources/shaders/sprite.vert", GL_VERTEX_SHADER);
    fs = create_shader("resources/shaders/sprite.frag", GL_FRAGMENT_SHADER);

    __spr.spriteProg = glCreateProgram();
    glAttachShader(__spr.spriteProg, vs);
    glAttachShader(__spr.spriteProg, fs);
    glLinkProgram(__spr.spriteProg);
    int link_ok;
    glGetProgramiv(__spr.spriteProg, GL_LINK_STATUS, &link_ok);
    if (!link_ok) {
        printf("glLinkProgram:");
        print_log(__spr.spriteProg);
        printf("\n");
    }

    __spr.u_size = getShaderLocation(shaderUniform, __spr.spriteProg, "u_size");
    __spr.opm_uniform =
        getShaderLocation(shaderUniform, __spr.spriteProg, "opm_uniform");
    __spr.texture_uniform =
        getShaderLocation(shaderUniform, __spr.spriteProg, "texture_uniform");

    __spr.vert_attrib = getShaderLocation(shaderAttrib, __spr.spriteProg, "vert_attrib");
    __spr.uv_attrib = getShaderLocation(shaderAttrib, __spr.spriteProg, "uv_attrib");


    glGenBuffers(1, &__spr.quadvbo);
    glBindBuffer(GL_ARRAY_BUFFER, __spr.quadvbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 3 * 6, quadVertices,
                 GL_STATIC_DRAW);

    glGenBuffers(1, &__spr.texvbo);
    glBindBuffer(GL_ARRAY_BUFFER, __spr.texvbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 2 * 6, texCoord,
                 GL_STATIC_DRAW);

}
void simplex(struct s_best *p_best, struct s_data *p_data, void *p_params_simplex, double (*f_simplex)(const gsl_vector *, void *), double CONVERGENCE_STOP_SIMPLEX, int M, enum plom_print print_opt)
{
  /* simplex algo using GSL. Straightforward adaptation of the GSL doc
     example */

  char str[255];

  FILE *p_file_trace = NULL;
  if(print_opt & PLOM_PRINT_BEST) {
      p_file_trace = plom_fopen(SFR_PATH, GENERAL_ID, "trace", "w", header_trace, p_data);
  }

  double log_like = 0.0;

  const gsl_multimin_fminimizer_type *T = gsl_multimin_fminimizer_nmsimplex2;
  gsl_multimin_fminimizer *simp = NULL;
  gsl_multimin_function minex_func;

  int iter = 0;
  int status;
  double size;

  gsl_vector *x = gsl_vector_alloc(p_best->n_to_be_estimated);
  gsl_vector *jump_sizes = gsl_vector_alloc(p_best->n_to_be_estimated);

  int k;
  for (k=0; k<p_best->n_to_be_estimated; k++) {
      gsl_vector_set(x, k, gsl_vector_get(p_best->mean, p_best->to_be_estimated[k]));
      gsl_vector_set(jump_sizes, k, sqrt(gsl_matrix_get(p_best->var, p_best->to_be_estimated[k], p_best->to_be_estimated[k]))); //note the sqrt !!
  }

  /* Initialize method and iterate */
  minex_func.n = p_best->n_to_be_estimated;
  minex_func.f = f_simplex;
  minex_func.params = p_params_simplex;

  simp = gsl_multimin_fminimizer_alloc(T, p_best->n_to_be_estimated );

  gsl_multimin_fminimizer_set(simp, &minex_func, x, jump_sizes);

  do
    {
#if FLAG_JSON //for the webApp, we block at every iterations to prevent the client to be saturated with msg
        block();
#endif

      iter++;
      status = gsl_multimin_fminimizer_iterate(simp);
      if (status) break;
      size = gsl_multimin_fminimizer_size(simp);
      status = gsl_multimin_test_size(size, CONVERGENCE_STOP_SIMPLEX);

      log_like = - gsl_multimin_fminimizer_minimum(simp);

      if (!(print_opt & PLOM_QUIET)) {
	  if (status == GSL_SUCCESS) {
	      print_log ("converged to maximum !");
	  }
	  sprintf(str, "%5d logLike = %12.5f size = %.14f", iter, log_like, size);
	  print_log(str);
      }

      transfer_estimated(p_best, gsl_multimin_fminimizer_x(simp), p_data);

      if(print_opt & PLOM_PRINT_BEST){
          print_trace(p_file_trace, iter-1, p_best, p_data, log_like);
      }

    } while (status == GSL_CONTINUE && iter < M);

  if(!(print_opt & PLOM_PRINT_BEST)){
      p_file_trace = plom_fopen(SFR_PATH, GENERAL_ID, "trace", "w", header_trace, p_data);
      print_trace(p_file_trace, iter-1, p_best, p_data, log_like);
  }

  plom_fclose(p_file_trace);

  gsl_multimin_fminimizer_free(simp);
  gsl_vector_free(x);
  gsl_vector_free(jump_sizes);
}
Esempio n. 11
0
//这种异步非阻塞的模式,带来高性能的同时需要开设空间保存还在等待异步返回的数据,如:redis回调的顺序链表,保存connector的哈希表
void * worker_loop(void *param)
{
    worker_t pworker = (worker_t)param;
    pworker->tid = pthread_self();

    int nfds = 0;
    int timeout = 100;
    struct epoll_event evs[4096];
    connector_t pconn = NULL;
    int i;

    while (1)
    {
        nfds = epoll_wait(pworker->epfd, evs, 4096, timeout);

        if (nfds == -1)
        {
            if (errno == EINTR)
                continue;

            print_log(LOG_TYPE_ERROR, "worker epoll_wait error, epfd = %d, errno = %d", pworker->epfd, errno);
            break;
        }

        for (i = 0; i < nfds; i++)
        {
            pconn = (connector_t)evs[i].data.ptr;

            if (evs[i].events & EPOLLIN)
            {
                worker_handle_read(pconn, evs[i].events);
            }
            if (evs[i].events & EPOLLOUT)
            {
                worker_handle_write(pconn);
            }
            if ((evs[i].events & EPOLLERR) || (evs[i].events & EPOLLHUP))
            {
                print_log(LOG_TYPE_DEBUG, "EPOLLERR Or EPOLLHUP Event Occure");
                pworker->neterr_count++;

                connector_close(pconn);
            }
            if (evs[i].events & EPOLLRDHUP)
            {
                connector_unsig_read(pconn);
                connector_unsig_rdhup(pconn);

                //可以在应用层面(写缓冲区)检查数据是否已经完全发出,server发出去,系统层面会在close后根据SO_LINGER的设置处理
                print_log(LOG_TYPE_DEBUG, "EPOLLRDHUP Event Occure");
                pworker->closed_count++;

                if (buffer_readable(pconn->pwritebuf) > 0)
                    connector_write(pconn);
                else
                    connector_close(pconn);
            }

        }

        handle_time_check(pworker);
    }

    return NULL;
}
Esempio n. 12
0
void display_information(int sig)
{

	print_log(INFO,"\n-----------------------------SERVER iNFO-----------------------------");
	print_log(ERROR,"\nCURRENT LOG LEVELS              : ERROR");
	print_log(WARNING,",WARNING");
	print_log(INFO,",INFO");
	print_log(DEBUG,",DEBUG");
	print_log(INFO,"\nDocument Root                    : %s",path_root);
	print_log(INFO,"\nPort No                          : %d",port_number);
	print_log(INFO,"\nResponse Strategy                : %s",strategy_name);
	
	if(strstr(strategy_name,"Fork")) 
	{	
		
		print_log(INFO,"\n---------------------------------------------------------------------\n");
		return;
	}
	if(strcmp(strategy_name,"Thread Pool")==0)
	{
		print_log(INFO,"\nThread Pool Size                 : %d",worker_max);
		print_log(INFO,"\nWorker Size        	         : %d",buffer_max);
	}

	print_log(INFO,"\nTotal Requests handled           : %d",show_total_requests());
	print_log(INFO,"\nTotal amount of data transferred : %d bytes",show_total_size());
	s_stop(&total_uptime);
	get_time_difference(&total_uptime);
	print_log(INFO,"\nTotal uptime                     : %s",show_time_difference(&total_uptime));
	print_log(INFO,"\nTotal time spent serving requets : %s",show_total_time_difference(&requests_time));

	print_log(INFO,"\nAvg time spent serving requests  : %s",show_average_time(&requests_time,show_total_requests()));
	print_log(INFO,"\n---------------------------------------------------------------------\n");
}
s32 tuner_select(HANDLE handle, DEVICEID devid,
		enum PRODUCT_TYPE product, enum BROADCAST_TYPE broadcast)
{
	switch (product) {
	case FC8300_TUNER:
		tuner = &fc8300_tuner;
		tuner_addr = FC8300_TUNER_ADDR;
		broadcast_type = broadcast;
		break;
	}

	if (tuner == NULL)
	{
			print_log(0,"ERROR tuner == NULL\n");
		return BBM_E_TN_SELECT;
	}
	if (tuner->init(handle, devid, broadcast))
	{
			print_log(0,"tuner->init\n");
		return BBM_E_TN_INIT;
	}
	fc8300_set_broadcast_mode(handle, devid, broadcast);

#ifdef BBM_ES
	if (product == FC8300_TUNER) {
		u8 chip_ver = 0x00;
		tuner_i2c_read(handle, devid, 0xff, 1, &chip_ver, 1);

		if (chip_ver == 0xc0)
			return BBM_OK;

		bbm_byte_write(handle, DIV_MASTER, BBM_RESYNC_ENABLE, 0xcf);
		bbm_long_write(handle, DIV_BROADCAST, BBM_MEMORY_RWM0,
							0x05555555);
		bbm_byte_write(handle, DIV_BROADCAST, BBM_SFS_FTS_ERR_MAX_1SEG,
							0x08);
		bbm_byte_write(handle, DIV_BROADCAST, BBM_SFS_FTS_ERR_MAX_3SEG,
							0x08);
		bbm_byte_write(handle, DIV_BROADCAST, BBM_PGA_GAIN_MAX, 0x0c);
		bbm_byte_write(handle, DIV_BROADCAST, BBM_CSF_GAIN_MAX, 0x09);
		bbm_byte_write(handle, DIV_MASTER, BBM_FD_OUT_MODE, 0x03);
		bbm_byte_write(handle, DIV_MASTER, BBM_DIV_START_MODE, 0x17);
		bbm_byte_write(handle, DIV_BROADCAST,
					BBM_PSAT_ON_REF_1SEG_QPSK, 0x1a);
		bbm_byte_write(handle, DIV_BROADCAST,
					BBM_PSAT_ON_REF_1SEG_16QAM, 0x1b);

		switch (broadcast) {
		case ISDBT_1SEG:
		case ISDBTMM_1SEG:
		case ISDBTSB_1SEG:
		case ISDBT_CATV_1SEG:
		case ISDBTSB_3SEG:
			bbm_byte_write(handle, DIV_BROADCAST, BBM_SFS_MTH,
							0x32);
			break;
		case ISDBT_13SEG:
		case ISDBTMM_13SEG:
		case ISDBT_CATV_13SEG:
			bbm_byte_write(handle, DIV_BROADCAST, BBM_SFS_MTH,
							0x31);
			break;
		}

#if defined(BBM_2_DIVERSITY) || defined(BBM_4_DIVERSITY)
		bbm_byte_write(handle, DIV_MASTER, BBM_XTAL_OUTBUF_EN, 0x00);
		bbm_byte_write(handle, DIV_MASTER, BBM_XTAL_OUTBUF_GAIN, 0x03);
		bbm_word_write(handle, DIV_BROADCAST, BBM_FD_RD_LATENCY_1SEG,
								0x1840);
		bbm_byte_write(handle, DIV_BROADCAST, BBM_COMB_OFF, 0x80);
#else /* SINGLE */
		bbm_word_write(handle, DIV_BROADCAST, BBM_FD_RD_LATENCY_1SEG,
								0x0002);
#endif /* #if defined(BBM_2_DIVERSITY) || defined(BBM_4_DIVERSITY) */
	}
#endif /* #ifdef BBM_ES */

	return BBM_OK;
}
Esempio n. 14
0
void read_next_byte_seq(WEATHERSTATION ws) {
  print_log(3,"read_next_byte_seq");
  write_bit(ws,0);
  set_RTS(ws,0);
  nanodelay();
}
int    broadcast_fc8300_drv_if_get_sig_info(struct broadcast_dmb_control_info *pInfo)
{
    int layer;
    static unsigned int before_irq_flag=0;

    print_log(NULL, "[FC8300] broadcast_drv_if_get_sig_info  %d, %d\n", OnAir, pInfo->cmd_info.cmd);
    if(OnAir == 0 || pInfo==NULL) {
        return ERROR;
    }

    layer = pInfo->cmd_info.layer;

    if((TimeCount_ms() - fcTimer) > 500) {
        if(before_irq_flag == irq_cnt)
        {
            tunerbb_drv_fc8300_Get_SignalInfo(&st, broad_type);
            print_log(NULL, "[FC8300] direct broadcast_drv_if_get_sig_info\n");
        }
        else
        {
            before_irq_flag = irq_cnt;
        }
        setTimer();
    }

    switch(pInfo->cmd_info.cmd)
    {
    case ENUM_GET_ALL:
        pInfo->sig_info.info.mmb_info.cn =
            st.cn;

        if(layer==0) {
            pInfo->sig_info.info.mmb_info.ber_a =
                st.ber_a;
            pInfo->sig_info.info.mmb_info.per_a =
                st.per_a;
            pInfo->sig_info.info.mmb_info.total_tsp_a =
                st.total_tsp_a;
            pInfo->sig_info.info.mmb_info.layerinfo_a =
                st.layerinfo_a;
        } else if(layer==1) {
            pInfo->sig_info.info.mmb_info.ber_b =
                st.ber_b;
            pInfo->sig_info.info.mmb_info.per_b =
                st.per_b;
            pInfo->sig_info.info.mmb_info.total_tsp_b =
                st.total_tsp_b;
            pInfo->sig_info.info.mmb_info.layerinfo_b =
                st.layerinfo_b;
        } else if(layer==2) {
            pInfo->sig_info.info.mmb_info.ber_c =
                st.ber_c;
            pInfo->sig_info.info.mmb_info.per_c =
                st.per_c;
            pInfo->sig_info.info.mmb_info.total_tsp_c =
                st.total_tsp_c;
            pInfo->sig_info.info.mmb_info.layerinfo_c =
                st.layerinfo_c;
        } else {
            pInfo->sig_info.info.mmb_info.ber_a =
                st.ber_a;
            pInfo->sig_info.info.mmb_info.per_a =
                st.per_a;
            pInfo->sig_info.info.mmb_info.ber_b =
                st.ber_b;
            pInfo->sig_info.info.mmb_info.per_b =
                st.per_b;
            pInfo->sig_info.info.mmb_info.ber_c =
                st.ber_c;
            pInfo->sig_info.info.mmb_info.per_c =
                st.per_c;
            pInfo->sig_info.info.mmb_info.total_tsp_a =
                st.total_tsp_a;
            pInfo->sig_info.info.mmb_info.total_tsp_b =
                st.total_tsp_b;
            pInfo->sig_info.info.mmb_info.total_tsp_c =
                st.total_tsp_c;
            pInfo->sig_info.info.mmb_info.layerinfo_a =
                st.layerinfo_a;
            pInfo->sig_info.info.mmb_info.layerinfo_b =
                st.layerinfo_b;
            pInfo->sig_info.info.mmb_info.layerinfo_c =
                st.layerinfo_c;
        }

        pInfo->sig_info.info.mmb_info.tmccinfo =
            st.tmccinfo;

        pInfo->sig_info.info.mmb_info.receive_status =
            st.receive_status;

        pInfo->sig_info.info.mmb_info.rssi =
            st.rssi;

        pInfo->sig_info.info.mmb_info.scan_status =
            st.scan_status;

        pInfo->sig_info.info.mmb_info.sysinfo =
            st.sysinfo;

        pInfo->cmd_info.over=
            st.agc;

        pInfo->sig_info.info.mmb_info.antenna_level_fullseg =
            st.antenna_level_fullseg;

        pInfo->sig_info.info.mmb_info.antenna_level_oneseg =
            st.antenna_level_oneseg;

    break;

    case ENUM_GET_BER:
        if(layer==0) {
            pInfo->sig_info.info.mmb_info.ber_a =
                    st.ber_a;
            pInfo->sig_info.info.mmb_info.total_tsp_a =
                    st.total_tsp_a;
        } else if(layer==1) {
            pInfo->sig_info.info.mmb_info.ber_b =
                    st.ber_b;
            pInfo->sig_info.info.mmb_info.total_tsp_b =
                    st.total_tsp_b;
        } else if(layer==2) {
            pInfo->sig_info.info.mmb_info.ber_c =
                    st.ber_c;
            pInfo->sig_info.info.mmb_info.total_tsp_c =
                    st.total_tsp_c;
        } else {
            pInfo->sig_info.info.mmb_info.ber_a =
                    st.ber_a;
            pInfo->sig_info.info.mmb_info.total_tsp_a =
                    st.total_tsp_a;
            pInfo->sig_info.info.mmb_info.ber_b =
                    st.ber_b;
            pInfo->sig_info.info.mmb_info.total_tsp_b =
                    st.total_tsp_b;
            pInfo->sig_info.info.mmb_info.ber_c =
                    st.ber_c;
            pInfo->sig_info.info.mmb_info.total_tsp_c =
                    st.total_tsp_c;
        }

    break;

    case ENUM_GET_PER:
        if(layer==0) {
            pInfo->sig_info.info.mmb_info.per_a =
                    st.per_a;
            pInfo->sig_info.info.mmb_info.total_tsp_a =
                    st.total_tsp_a;
        } else if(layer==1) {
            pInfo->sig_info.info.mmb_info.per_b =
                    st.per_b;
            pInfo->sig_info.info.mmb_info.total_tsp_b =
                    st.total_tsp_b;
        } else if(layer==2) {
            pInfo->sig_info.info.mmb_info.per_c =
                    st.per_c;
            pInfo->sig_info.info.mmb_info.total_tsp_c =
                    st.total_tsp_c;
        } else {
            pInfo->sig_info.info.mmb_info.per_a =
                    st.per_a;
            pInfo->sig_info.info.mmb_info.total_tsp_a =
                    st.total_tsp_a;
            pInfo->sig_info.info.mmb_info.per_b =
                    st.per_b;
            pInfo->sig_info.info.mmb_info.total_tsp_b =
                    st.total_tsp_b;
            pInfo->sig_info.info.mmb_info.per_c =
                    st.per_c;
            pInfo->sig_info.info.mmb_info.total_tsp_c =
                    st.total_tsp_c;
        }
    break;

    case ENUM_GET_CN:
        pInfo->sig_info.info.mmb_info.cn =
            st.cn;
        print_log(NULL, "[mmbi][monitor] cn[%d]\n",
                pInfo->sig_info.info.mmb_info.cn);
    break;

    case ENUM_GET_CN_PER_LAYER:
        pInfo->sig_info.info.mmb_info.cn =
            st.cn;
        print_log(NULL, "[mmbi][monitor] cn[%d]\n",
                pInfo->sig_info.info.mmb_info.cn);
    break;

    case ENUM_GET_LAYER_INFO:
        if(layer==0) {
            pInfo->sig_info.info.mmb_info.layerinfo_a =
                st.layerinfo_a;
        } else if(layer==1) {
            pInfo->sig_info.info.mmb_info.layerinfo_b =
                st.layerinfo_b;
        } else if(layer==2) {
            pInfo->sig_info.info.mmb_info.layerinfo_c =
                st.layerinfo_c;
        } else {
            pInfo->sig_info.info.mmb_info.layerinfo_a =
                st.layerinfo_a;
            pInfo->sig_info.info.mmb_info.layerinfo_b =
                st.layerinfo_b;
            pInfo->sig_info.info.mmb_info.layerinfo_c =
                st.layerinfo_c;
        }
    break;

    case ENUM_GET_RECEIVE_STATUS:
        pInfo->sig_info.info.mmb_info.receive_status =
                st.receive_status;
        print_log(NULL, "[mmbi][monitor]  rcv status[%d]\n",
                pInfo->sig_info.info.mmb_info.receive_status);
        /* for debugging log */
    break;

    case ENUM_GET_RSSI:
        pInfo->sig_info.info.mmb_info.rssi =
            st.rssi;
        print_log(NULL, "[mmbi][monitor]  rssi[%d]\n",
                pInfo->sig_info.info.mmb_info.rssi);
    break;

    case ENUM_GET_SCAN_STATUS:
        pInfo->sig_info.info.mmb_info.scan_status =
            st.scan_status;
        print_log(NULL, "[mmbi][monitor]  scan status[%d]\n",
                pInfo->sig_info.info.mmb_info.scan_status);
        /* for debugging log */
    break;

    case ENUM_GET_SYS_INFO:
        pInfo->sig_info.info.mmb_info.sysinfo =
            st.sysinfo;
        print_log(NULL, "[mmbi][monitor]  sys info[%d]\n",
                pInfo->sig_info.info.mmb_info.sysinfo);
        /* for debugging log */
    break;

    case ENUM_GET_TMCC_INFO:
        pInfo->sig_info.info.mmb_info.tmccinfo =
            st.tmccinfo;
        print_log(NULL, "[mmbi][monitor]  tmcc info[%d]\n",
                pInfo->sig_info.info.mmb_info.tmccinfo);
        /* for debugging log */
    break;

    case ENUM_GET_ONESEG_SIG_INFO:
        broadcast_fc8300_drv_if_get_oneseg_sig_info(&st, pInfo, broad_type);
    break;

    default:
        print_log(NULL, "[mmbi][monitor] sig_info unknown command[%d]\n",
                pInfo->cmd_info.cmd);
        return -1;
    break;
    }

    return OK;
}
Esempio n. 16
0
static int
do_btree_test(struct client *cli)
{
  memcached_coll_create_attrs_st create_attr;
  memcached_return rc;
  int ok, keylen, base;
  const char *key;
  uint64_t bkey;
  uint8_t *val_ptr;
  int val_len;

  // Pick a key
  key = keyset_get_key(cli->ks, &base);
  keylen = strlen(key);

  // Create a btree item
  if (0 != client_before_request(cli))
    return -1;

  memcached_coll_create_attrs_init(&create_attr, 20 /* flags */,
    100 /* exptime */, 4000 /* maxcount */);  
  memcached_coll_create_attrs_set_overflowaction(&create_attr,
    OVERFLOWACTION_SMALLEST_TRIM);
  rc = memcached_bop_create(cli->next_mc, key, keylen, &create_attr);
  ok = (rc == MEMCACHED_SUCCESS);
  if (!ok) {
    print_log("bop create failed. id=%d key=%s rc=%d(%s)", cli->id, key,
      rc, memcached_strerror(NULL, rc));
  }
  if (0 != client_after_request(cli, ok))
    return -1;

  // Insert 1000 elements
  for (bkey = base; bkey < base + 1000; bkey++) {
    char bkey_buf[32];
    int bkey_len;
    
    if (0 != client_before_request(cli))
      return -1;

    bkey_len = sprintf(bkey_buf, "%d", (int)bkey);

    val_ptr = NULL;
    val_len = valueset_get_value(cli->vs, &val_ptr);
    assert(val_ptr != NULL && val_len > 0 && val_len <= 4096);
    
    rc = memcached_bop_ext_insert(cli->next_mc, key, keylen,
      (const unsigned char*)bkey_buf,  bkey_len,
      NULL /* eflag */, 0 /* eflag length */,
      (const char*)val_ptr, (size_t)val_len,
      NULL /* Do not create automatically */);
    valueset_return_value(cli->vs, val_ptr);
    ok = (rc == MEMCACHED_SUCCESS);
    if (!ok) {
      print_log("bop insert failed. id=%d key=%s bkey=%llu rc=%d(%s)",
        cli->id, key, (long long unsigned)bkey,
        rc, memcached_strerror(NULL, rc));
    }
    if (0 != client_after_request(cli, ok))
      return -1;
  }

  return 0;
}
Esempio n. 17
0
	LogView::LogView()
		: m_text_area( new QTextEdit() )
	{
#ifdef _DEBUG
		setVisible( true );
#else
		setVisible( false );
#endif

		setWindowTitle(tr("Log"));
		setWidget( m_text_area.get() );

		m_text_area->setReadOnly(true);
		
		util::register_log_output( [&]( util::Log::Level level, const std::string& message ){ print_log( level, message ); }, 1 );

	}
Esempio n. 18
0
int _ant_send_message(asm_t* self, uchar_t msg_id, uchar_t channel,
                      const uchar_t data[], uchar_t data_size,
                      ant_msg_t* response) {
    uchar_t msgbuffer[sizeof(ant_msg_t) + 1];    /* message + sync byte */
    ant_msg_t *msg = (ant_msg_t*)(msgbuffer+1);
    uchar_t chksum, *p;
    size_t msg_size = (sizeof(msg->id)
                       +sizeof(msg->size)
                       +sizeof(msg->channel)
                       +data_size);
    int i, error, retry=0;

    if (_keyboard_interrupted())
        return MR_ABORTED;

    if (ant_is_recovering(self))
        return MR_RECOVERING;

    /*@cstart(build message)*/
    msgbuffer[0] = MESG_TX_SYNC;
    msg->size = data_size+1; /* +1 for channel */
    msg->id = msg_id;
    msg->channel = channel;
    memcpy(msg->data, data, data_size);

    chksum = 0;
    for (i = 0, p = msgbuffer; i < (int)msg_size+1; i++, p++)
        chksum ^= *p;

    msg->data[data_size++] = chksum;
    msg->data[data_size++] = 0;
    msg->data[data_size] = 0;

#if _DEBUG_LEVEL >= 1
    print_log("#_ant_send_message: %s(%i) ",
              get_message_name(msg->id),
              (int)msg->channel);
    print_message_bytes(msg);
    print_log("-%u\n", (ushort_t)(ant_clock() & 0xFFFF));
#endif

    if (ant_is_waiting_for_response(self))
        CHECK(MR_WRONG_STATE);

    /*@(build message)*/

_try_again:

    CHECK(_ant_write(self, msgbuffer, msg_size+4));
    /* 4 == +sizeof(sync)+sizeof(checksum)+2*sizeof(0) */

    error = _ant_wait_for_response(self, msg, response, 0);

    /*@cstart(time out handling)*/
    if (error == MR_TIMEOUT
            && retry < 10
            && msg_id != MESG_ACKNOWLEDGED_DATA_ID
            && msg_id != MESG_BURST_DATA_ID) {
        char zeros[15];

        retry++;
        memset(zeros, 0, sizeof(zeros));
        _ant_write(self, zeros, sizeof(zeros));
        goto _try_again;
    }
    /*@(time out handling)*/

    CHECK(error);

    BEGIN_EXCEPT;
    print_exception();
    END_EXCEPT;

    return error;
}
static int broadcast_Isdb_i2c_suspend(struct i2c_client* client, pm_message_t mesg)
{
	int rc = 0;
	print_log(NULL, "[%s]\n", __func__);
	return rc;
}
Esempio n. 20
0
void * jpeg_highlighter_analyze(JOB_ARG *job)
{
	int ii, jj, kk;
	int row;
	int col;

	long long red_sum = 0;
	long long green_sum = 0;
	long long blue_sum = 0;

	guchar max_pixel_color[4];

	union
	{
		guchar pixel[4];
		unsigned int value;
	} stuff;

	gint32 layer_id;
	int temp = 0;
	int unique_compressed_colors = 0;
	int unique_original_colors = 0;

	int *histogram;

	max_pixel_color[0] = 0;
	max_pixel_color[1] = 0;
	max_pixel_color[2] = 0;
	max_pixel_color[3] = 0;

	histogram = (int*)malloc(sizeof(int)*255*255*255);
//
//	GimpRunMode mode = GIMP_RUN_NONINTERACTIVE;
//	PIXEL **temp_array;
GimpPixelRgn rgn_in;

	printf("in analizer\n");

	job->drawable->drawable_id = gimp_image_get_active_drawable(job->image_id);

	layer_id = gimp_image_get_active_layer(job->image_id);

//	printf("adding alpha channel\n");
//	gimp_layer_add_alpha(layer_id);
//
//
////	if(! gimp_drawable_has_alpha (layer_id))
////	{
////		 /* some filtermacros do not work with layer that do not have an alpha channel
////		 * and cause gimp to fail on attempt to call gimp_pixel_rgn_init
////		  * with both dirty and shadow flag set to TRUE
////		  * in this situation GIMP displays the error message
////		  *    "expected tile ack and received: 5"
////		  *    and causes the called plug-in to exit immediate without success
////		  * Therfore always add an alpha channel before calling a filtermacro.
////		  */
////		  gimp_layer_add_alpha(layer_id);
////		  printf("adding alpha channel\n");
////   }


	printf("zeroed array\n");

	for(ii = 0; ii < 255*255*255; ii++)
	{
		histogram[ii] = 0;
	}

	gimp_pixel_rgn_init(&rgn_in, job->drawable, job->start_colum, job->start_row, job->image.width, job->image.height, FALSE, FALSE);

	for (row = 0; row < job->image.height; row++)
	{
		for (col = 0; col < job->image.width; col++)
		{
			gimp_pixel_rgn_get_pixel (&rgn_in, stuff.pixel, col,row);

			job->array_out[col][row].red = stuff.pixel[0];
			job->array_out[col][row].green = stuff.pixel[1];
			job->array_out[col][row].blue = stuff.pixel[2];

			red_sum += stuff.pixel[0];
			green_sum += stuff.pixel[1];
			blue_sum += stuff.pixel[2];

			stuff.pixel[3] = 0;

			if(stuff.pixel[0] + stuff.pixel[1]+ stuff.pixel[2] > max_pixel_color[0] +  max_pixel_color[1] +  max_pixel_color[2] )
			{
				max_pixel_color[0] = stuff.pixel[0];
				max_pixel_color[1] = stuff.pixel[1];
				max_pixel_color[2] = stuff.pixel[2];
			}

			histogram[stuff.value]++;

		}

		if (row % 50 == 0)
		{
			gimp_progress_update ((gdouble) row / job->image.height);

		}
	}

	for(ii = 0; ii < 255*255*255; ii++)
	{	
		if(histogram[ii] != 0)
		{
			unique_compressed_colors++;
		}
	}

	//doing the original

	printf("zeroed array\n");

	for(ii = 0; ii < 255*255*255; ii++)
	{
		histogram[ii] = 0;
	}


	for (row = 0; row < job->image.height; row++)
	{
		for (col = 0; col < job->image.width; col++)
		{
			stuff.pixel[0] = job->array_in[col][row].red;
			stuff.pixel[1] = job->array_in[col][row].green;
			stuff.pixel[2] = job->array_in[col][row].blue;

			stuff.pixel[3] = 0;

			histogram[stuff.value]++;

		}
	}

	for(ii = 0; ii < 255*255*255; ii++)
	{
		if(histogram[ii] != 0)
		{
			unique_original_colors++;
		}
	}

	free(histogram);

	print_log("\nJpeg compression difference\n",temp);
	print_log("unique colors in original image:%d\n",unique_original_colors);
	print_log("unique colors in compressed image:%d\n",unique_compressed_colors);
	print_log("ratio: %f\n",(double)unique_original_colors/unique_compressed_colors);
	print_log("brightest compressed color %d %d %d\n",max_pixel_color[0], max_pixel_color[1], max_pixel_color[2]);
	print_log("avg compressed color %f %f %f\n",(float)red_sum/(job->image.height*job->image.width), (float)green_sum/(job->image.height*job->image.width),(float)blue_sum/(job->image.height*job->image.width));
}
Esempio n. 21
0
int my_lua_printlog(lua_State *state)
{
    print_log(g_hwdev);
    return 0;
}
Esempio n. 22
0
int main(int argc, char **argv) {
    uint64_t hidden_layer_size = 100;
    int min_count = 5;
    TrainPara train_para;
    string save_vocab_file;
    string read_vocab_file;
    string train_file;
    string vector_file;

    if (argc < 3) {
        cerr << usage << endl;
        return -1;
    }
    train_file = argv[argc - 2];
    vector_file = argv[argc - 1];
    
    for (int i = 1; i < argc - 2; i += 2) {
        string arg = argv[i];
        const char* val = argv[i + 1];

        if (arg == "-size") {
            hidden_layer_size = atoi(val);
        }
        else if (arg == "-type") {
            if (string(val) == "cbow") {
                train_para.type = CBOW;
            }
            else if (string(val) == "skip-gram") {
                train_para.type = SKIP_GRAM;
            }
            else {
                cerr << "unknown -type: " << val << endl;;
                return -1;
            }
        }
        else if (arg == "-algo") {
            if (string(val) == "ns") {
                train_para.algo = NEG_SAMPLING;
            }
            else if (string(val) == "hs") {
                train_para.algo = HIER_SOFTMAX;
            }
            else {
                cerr << "unknown -algo: " << val << endl;;
                return -1;
            }
        }
        else if (arg == "-neg-sample") {
            train_para.neg_sample_cnt = atoi(val);
        }
        else if (arg == "-window") {
            train_para.window_size = atoi(val);
        }
        else if (arg == "-subsample") {
            train_para.subsample_thres = atof(val);
        }
        else if (arg == "-thread") {
            train_para.thread_cnt = atoi(val);
        }
        else if (arg == "-iter") {
            train_para.iter_cnt = atoi(val);
        }
        else if (arg == "-min-count") {
            min_count = atoi(val);
        }
        else if (arg == "-alpha") {
            train_para.alpha = atof(val);
        }
        else if (arg == "-save-vocab") {
            save_vocab_file = val;
        }
        else if (arg == "-read-vocab") {
            read_vocab_file = val;
        }
        else {
            cerr << "unknow argument: '" << arg << "'" << endl;
            return -1;
        }
    }

    if (train_para.alpha < 0) {
        if (train_para.type == CBOW) {
            train_para.alpha = 0.05;
        }
        else {
            train_para.alpha = 0.025;
        }
    }

    cerr << "parameters:" << endl
         << "size = " << hidden_layer_size << endl
         << "type = " << ((train_para.type==CBOW)?"cbow":"skip-gram") << endl
         << "algo = " << ((train_para.algo==HIER_SOFTMAX)?"hs":"neg sampling") << endl
         << "neg sampling cnt = " << train_para.neg_sample_cnt << endl
         << "window = " << train_para.window_size << endl
         << "subsample thres = " << train_para.subsample_thres << endl
         << "thread = " << train_para.thread_cnt << endl
         << "iter = " << train_para.iter_cnt << endl
         << "min count = " << min_count << endl
         << "alpha = " << train_para.alpha << endl
         << "save vocab = " << save_vocab_file << endl
         << "read vocab = " << read_vocab_file << endl
         << "training file = " << train_file << endl
         << "word vector file = " << vector_file << endl
         << endl;
    print_log("start ...");

    ifstream ifs_train(train_file.c_str());
    if (!ifs_train) {
        cerr << "can't open: " << train_file << endl;
        return -1;
    }
    
    Vocabulary vocab;
    HuffmanTree* huffman_tree = NULL;
    vocab.parse(ifs_train, min_count);
    cerr << "vocab size = " << vocab.size() << ", total words count = " << vocab.total_cnt() << endl;
    print_log("calc vocab finished ...");
    ifs_train.close();

    if (!save_vocab_file.empty()) {
        ofstream ofs_vocab(save_vocab_file.c_str());
        if (!ofs_vocab) {
            cerr << "can't write to " << save_vocab_file << endl;
            return -1;
        }
        vocab.save(ofs_vocab);
        print_log("save vocab finished ...");
    }

    if (train_para.algo == NEG_SAMPLING) {
        vocab.init_sampling_table();
        print_log("init sampling table finished ...");
    }
    else if (train_para.algo == HIER_SOFTMAX) {
        huffman_tree = new HuffmanTree(vocab.vocab());
        print_log("grow huffman tree finished ...");
    }


    Net net(vocab.size(), hidden_layer_size);
    print_log("net init finished ...");

    if (!train(train_file, vocab, *huffman_tree, net, train_para)) {
        cerr << "training failed" << endl;
        return -1;
    }
    print_log("training finished ...");


    ofstream ofs_result(vector_file.c_str());
    if (!ofs_result) {
        cerr << "can't write to " << vector_file << endl;
        return -1;
    }
    save_word_vec(ofs_result, net, vocab);
    ofs_result.close();
    print_log("saving word vector finished ...");

    delete huffman_tree;
}
Esempio n. 23
0
/**
 * @brief Starts a Telnet bound control interface
 *
 * @return 0 on success, -1 on error
 */
int
ctrl_telnet_start (int port)
{
  /* Start by making us threadsafe... */
  pthread_mutex_lock (&startstop_lock);

  /* Create listener socket */
  ttd.listener = socket (PF_INET, SOCK_STREAM, 0);
  if (ttd.listener == -1)
  {
    perror ("socket");
    pthread_mutex_unlock (&startstop_lock);
    return -1;
  }

  /* Clears us from "address already in use" errors */
#ifndef WIN32
  if (setsockopt (ttd.listener, SOL_SOCKET, SO_REUSEADDR,
                  &yes, sizeof (int)) == -1)
#else
  if (setsockopt (ttd.listener, SOL_SOCKET, SO_REUSEADDR,
                  (const char *)&yes, sizeof (int)) == -1)
#endif
    perror ("setsockopt");

  ttd.local_address.sin_family = AF_INET;
  ttd.local_address.sin_addr.s_addr = INADDR_ANY;
  ttd.local_address.sin_port = htons (port);
  memset (&ttd.local_address.sin_zero, '\0',
          sizeof (ttd.local_address.sin_zero));

  if (bind (ttd.listener, (struct sockaddr *) &ttd.local_address,
            sizeof (ttd.local_address)) == -1)
  {
    perror ("bind");
    pthread_mutex_unlock (&startstop_lock);
    return -1;
  }

  if (listen (ttd.listener, CTRL_TELNET_BACKLOG) == -1)
  {
    perror ("listen");
    pthread_mutex_unlock (&startstop_lock);
    return -1;
  }

  print_log (ULOG_NORMAL, "Listening on telnet port %u\n", port);

  /* Create killer pipes */
  if (pipe (ttd.killer))
  {
    perror ("Failed to create killer pipe");
    pthread_mutex_unlock (&startstop_lock);
    return -1; /* FIXME. Kill all sockets... not critical,, but still */
  }

  if (pthread_create (&ttd.thread, NULL, ctrl_telnet_thread, NULL))
  {
    /* FIXME: Killall sockets... */
    perror ("Failed to create thread");
    pthread_mutex_unlock (&startstop_lock);
    return -1;
  }

  started = 1;
  ctrl_telnet_register_internals ();
  pthread_mutex_unlock (&startstop_lock);

  return 0;
}
Esempio n. 24
0
int Host_Info::load_oid_table_get(){
    unsigned int thread_id;
    struct snmp_session session;

    map<string,OID_Value_Table>::iterator iter;
    int fvalue=0;

    struct snmp_pdu *req, *resp;



    void *sp;
//    struct snmp_session *sptr;
    oid             name[MAX_OID_LEN];
    size_t          name_length=MAX_OID_LEN;
    oid             root[MAX_OID_LEN];
    size_t          rootlen=MAX_OID_LEN;
    struct variable_list *vars;


    char snmp_err_str[SNMP_ERR_STR_SIZE];
    char buf[512];
    char *placeholder;
    char buf2[512];
///
    string temp_string1,temp_string2;
    int running;
    int             status;
    int i;

    thread_id=(unsigned int) ((uint64_t)pthread_self());
    snmp_sess_init(&session);

    session.version   = SNMP_VERSION_2c;
    session.peername  = (char *)   ip_address.c_str();
    session.community = (u_char *) community.c_str();
    session.community_len = strlen(community.c_str());


    for (iter = oid_table.begin(); iter != oid_table.end(); iter++){

        assert(0==iter->first.compare(iter->second.oid));
        print_log(LOG_DEBUG,"Doing host=%s for oid %s\n",ip_address.c_str(),iter->first.c_str());


       rootlen = MAX_OID_LEN;
       //rootlen = strlen(iter->first.c_str());
       if (!read_objid(iter->first.c_str(), root, &rootlen)) {
       //if (!Read_objid_ts(iter->first.c_str(), root, &rootlen)) {

            //snmp_perror(argv[arg]);
            //exit(1);
          print_log(LOG_ERR,"Cannot parse the oid='%s' rootlen=%d  oid table get?\n",iter->first.c_str(),rootlen);
          snmp_perror("read_objid");
          return -1;
       }
       if(!(sp = snmp_sess_open(&session))){
          snmp_perror("snmp_open");
          print_log(LOG_WARNING,"[Thread %u] SNMP table builder, failed to open session to %s\n",thread_id,ip_address.c_str());

          return -1;
       }
////////////

  req = snmp_pdu_create(SNMP_MSG_GETNEXT);
  snmp_add_null_var(req, root, rootlen);

  status = snmp_sess_synch_response(sp,req,&resp);

  if(status == STAT_SUCCESS && resp->errstat == SNMP_ERR_NOERROR){
    char buf1[512];
    char *placeholder;
    int j;
    oid tmp[MAX_OID_LEN];
    char temp[MAX_OID_LEN];
    char ifIndexstr[MAX_OID_LEN];
    string value;
    uint64_t local_index;
 

    vars = resp->variables;

    //first = malloc(sizeof(struct Value_index_mapping));
    //assert(first!=NULL);

    //memset(buf1,'\0',sizeof(buf1));
    //memset(first->value,'\0',sizeof(first->value));
    //int toosmall = 
    snprint_value(buf1, sizeof(buf1), vars->name, vars->name_length, vars);
    placeholder = strstr(buf1,":");
    if(placeholder != NULL)
      placeholder = placeholder +2;
    if(strstr(placeholder,"\"")){
      placeholder = placeholder +1;
      //strncpy(first->value,placeholder,strlen(placeholder)-1);
      value=placeholder;
      value.resize(value.size()-1);
    }else{
      //strcpy(first->value,placeholder);
      value=placeholder;
    }



    memcpy(tmp,vars->name,vars->name_length * sizeof(oid));
    for(j=0;j<vars->name_length-rootlen;j++){
      if(j>0){
        i = sprintf(temp, ".%d", (int) tmp[rootlen+j]);
        strcat(ifIndexstr,temp);
      }else{
        i = sprintf(ifIndexstr, "%d", (int) tmp[rootlen+j]);
      }
    }
    //strcpy(first->index,ifIndexstr);
    temp_string2=ifIndexstr;

    local_index=atoll(temp_string2.c_str());
    assert(0==1); //this should never get here! under rev 3.1.0 initial
    //iter->second.indexof[value]=local_index;
    //iter->second.valueof[local_index]=value;
 
    //first->next = NULL;
    //current = first;
  }else{
    snprintf(snmp_err_str,SNMP_ERR_STR_SIZE-1,"Failure buidling snmp_table Hostname: %s snmp_sync_response",ip_address.c_str());
    snmp_perror(snmp_err_str);
    if(resp)
      snmp_free_pdu(resp);
    snmp_sess_close(sp);

    return -1;
  }



////////////////

       running=1;

       while(running==1) {
/////////
    oid tmp[MAX_OID_LEN];

    req = snmp_pdu_create(SNMP_MSG_GETNEXT);
    snmp_add_null_var(req,vars->name,vars->name_length);
    if(resp)
      snmp_free_pdu(resp);
    status = snmp_sess_synch_response(sp,req,&resp);

    if(status == STAT_SUCCESS && resp->errstat == SNMP_ERR_NOERROR){



      struct Value_index_mapping *tempIndex = NULL;
      char buf[512];
      char *placeholder;
      char ifIndexstr[MAX_OID_LEN];
      int j;
      char temp[MAX_OID_LEN];
      oid tmp[MAX_OID_LEN];
      string value_string;
      string index_string;
      int64_t local_index;
 
      vars = resp->variables;
      //tempIndex = malloc(sizeof(struct Value_index_mapping));  //why allocate a != struct?  
      //assert(tempIndex!=NULL);

      //memset(buf,'\0',sizeof(buf));
      //memset(tempIndex->value,'\0',sizeof(tempIndex->value));
      //will add a few extra bytes later, ensure we are covered
      snprint_value(buf, sizeof(buf)-5, vars->name, vars->name_length, vars);

      //printf("Raw Value = %s\n",buf);
      placeholder = strstr(buf,":");
      if(placeholder != NULL)
        placeholder = placeholder +2;
      if(strstr(placeholder,"\"")){
        placeholder = placeholder +1;
        //you assert on the size of the dest, not the origin
        assert(strlen(placeholder)+1<STD_STRING_SIZE);
        //strncpy(tempIndex->value,placeholder,strlen(placeholder));
        value_string=placeholder;
      }else{
        //strncpy(tempIndex->value,placeholder,STD_STRING_SIZE-1);
        value_string=placeholder;
        value_string.resize(value_string.size()-1);
      }

      memcpy(tmp,vars->name,vars->name_length * sizeof(oid));
      for(j=0;j<vars->name_length-rootlen;j++){
        if(j>0){
          i = sprintf(temp, ".%d",(int) tmp[rootlen+j]);
          strcat(ifIndexstr,temp);
        }else{
          i = sprintf(ifIndexstr, "%d",(int) tmp[rootlen+j]);
        }
      }
      //strcpy(tempIndex->index,ifIndexstr);
      index_string=ifIndexstr;

      local_index=atoll(index_string.c_str());
      assert(1==0); //this should never reach this under 3.1.0
      //iter->second.indexof[value_string]=local_index;
      //iter->second.valueof[local_index]=value_string;


      //print_log(LOG_DEBUG,"[Thread %u] Index = %u , Value = %s\n",thread_id,local_index,value_string.c_str());
      //current->next = tempIndex;
      //current = tempIndex;
      //current->next = NULL;
    }else{
      //snmp_perror("snmp_synch_response");
      //snprintf(snmp_err_str,SNMP_ERR_STR_SIZE-1,"[Thread %u] Hostname: %-15s snmp_sync_response",thread_id, hostInfo.name);
      snmp_perror(snmp_err_str);

      if(resp)
        snmp_free_pdu(resp);
      snmp_sess_close(sp);
      return -1;
    }

    //oid tmp[MAX_OID_LEN];
    memcpy(tmp,vars->name,vars->name_length * sizeof(oid));

    if(tmp[rootlen-1] != root[rootlen-1]){
      if(resp)
        snmp_free_pdu(resp);
      snmp_sess_close(sp);
      running=0;
      //done?
    }



//////////
       }      //end while


    }//end for each host

}
Esempio n. 25
0
static void pcap_handle_lan(u_char *user, const struct pcap_pkthdr *h, const u_char *buf)
{
	PACKET_HEADER* hdr = (PACKET_HEADER*)buf;
	int eap_type_int; // EAP中的type
	int eapol_type_int = hdr->eapol_hdr.type;
	MAC_CHECK_STATUS mac_status = proxy_check_mac_integrity(buf);

	switch (eapol_type_int) {
	case EAPOL_START:
		switch (mac_status) {
		case MAC_NOT_DEFINED:
			proxy_store_client_mac(buf); // 锁定客户端的MAC地址,以防不同设备的认证流程干扰
			print_log(_(">> 客户端%s正在发起认证\n"), formatHex(clientMAC, 6));
			proxyClientRequested = 1;
			switchState(ID_START);
			break;
		case MAC_CHECK_PASSED:
			if (proxySuccessCount < proxySuccessCount && (state == ID_ECHO || state == ID_WAITECHO)) {
				print_log(_("!! 客户端在认证完成后发送Start包,忽略\n"));
				goto DONE;
			} else {
				/* 这里一般是多次认证(-j参数大于1时) */
				print_log(_(">> 客户端%s再次发起认证\n"), formatHex(clientMAC, 6));
				switchState(ID_START);
			}
			break;
		case MAC_CHECK_FAILED:
			goto PROXY_INTERRUPTED;
		}
		break;
	case EAPOL_LOGOFF:
		switch (mac_status) {
		case MAC_CHECK_FAILED:
			goto PROXY_INTERRUPTED;
		case MAC_NOT_DEFINED:
			goto DONE;
		case MAC_CHECK_PASSED:
			print_log(_("!! 客户端要求断开认证,将忽略此请求\n"));
			goto DONE;
		}
	case EAP_PACKET:
		switch (mac_status) {
		case MAC_CHECK_FAILED:
			goto PROXY_INTERRUPTED;
		case MAC_NOT_DEFINED:
			goto DONE;
		case MAC_CHECK_PASSED:
			eap_type_int = hdr->eap_hdr.type;
			switch (eap_type_int) {
			case IDENTITY:
				print_log(_(">> 客户端已发送用户名\n"));
				break;
			case MD5_CHALLENGE:
				print_log(_(">> 客户端已发送密码\n"));
				break;
			}
			break;
		}
	}

	/*
	所有不需代理的情况均已处理完毕,
	现在将客户端发来的数据包中源MAC改为本设备的并发送出去
	*/
	proxy_send_to_wan(buf, h->len);
	goto DONE;

PROXY_INTERRUPTED:
	print_log(_("!! 认证流程受到来自%s的干扰!\n"), formatHex(hdr->eth_hdr.src_mac, 6));
DONE:
	return;
}
Esempio n. 26
0
///////////////////////////////////////////////////////////////
/// Given a host loads all the oid mappings for that host
/// Uses snmp bulk get to minimize the time required for each
/// mapping.
int Host_Info::load_oid_table(){
    unsigned int thread_id;
    struct snmp_session session;
    
    map<string,OID_Value_Table>::iterator iter;
    int fvalue=0;
////

    //netsnmp_session session, *ss;
    int             numprinted = 0;
    int             reps = 15, non_reps = 0;

    netsnmp_pdu    *pdu, *response=NULL;
    netsnmp_variable_list *vars;
    int             arg;
    oid             name[MAX_OID_LEN];
    size_t          name_length;
    oid             root[MAX_OID_LEN];
    size_t          rootlen;
    int             count;
    int             running;
    int             status;
    int             check;
    int             exitval = 0;

    struct snmp_pdu *req, *resp;
    void *sp;


    char snmp_err_str[SNMP_ERR_STR_SIZE];
    char buf[512];
    char *placeholder;
    char buf2[512];
///
    string temp_string1,temp_string2;
    int i;
////////////    


    thread_id=(unsigned int)((uint64_t) pthread_self());
    simple_snmp_sess_init(&session);

    session.retries=4;
    session.version   = SNMP_VERSION_2c;
    //ARE THE NEXT TWO LINES  VALID???!
    session.peername  = (char *)   ip_address.c_str();
    session.community = (u_char *) community.c_str();
    session.community_len = strlen(community.c_str());
   
    
    for (iter = oid_table.begin(); iter != oid_table.end(); iter++){
        /// 
        assert(0==iter->first.compare(iter->second.oid));
        print_log(LOG_INFO,"Doing host=%s for oid %s\n",ip_address.c_str(),iter->first.c_str());  
 

       rootlen = MAX_OID_LEN;
       //rootlen = strlen(iter->first.c_str());
       if (!read_objid(iter->first.c_str(), root, &rootlen)) {
       //if (!Read_objid_ts(iter->first.c_str(), root, &rootlen)) {

            //snmp_perror(argv[arg]);
            //exit(1);
          print_log(LOG_ERR,"Cannot parse the oid='%s' rootlen=%d host=%s\n",iter->first.c_str(),rootlen,ip_address.c_str());
          snmp_perror("read_objid");
          return -1;
       }
       if(!(sp = snmp_sess_open(&session))){
          snmp_perror("snmp_open");
          print_log(LOG_WARNING,"[Thread %u] SNMP table builder, failed to open session to %s\n",thread_id,ip_address.c_str());

          return -1;
       }
       running=1;
   
       //why memmove and not memcpy? ask the netsmpbulk writers
       memmove(name, root, rootlen * sizeof(oid));
       name_length = rootlen;
       //should be a while
       while(running==1){
            /*
            * create PDU for GETBULK request and add object name to request 
             */
            pdu = snmp_pdu_create(SNMP_MSG_GETBULK);
            pdu->non_repeaters = non_reps;
            pdu->max_repetitions = reps;    /* fill the packet */
            snmp_add_null_var(pdu, name, name_length);

            /*
            * do the request 
            */
            //status = snmp_synch_response(sp, pdu, &response);
            status = snmp_sess_synch_response(sp,pdu,&response);
            switch (status){
                case STAT_SUCCESS:
                      if (response->errstat == SNMP_ERR_NOERROR) {
                          //Yay success!
                          
//////////////
                for (vars = response->variables; vars;
                     vars = vars->next_variable) {
                    if ((vars->name_length < rootlen)
                        || (memcmp(root, vars->name, rootlen * sizeof(oid))
                            != 0)) {
                        /*
                         * not part of this subtree 
                         */
                        running = 0;
                        continue;
                    }
                    numprinted++;
                    //print_log(LOG_DEBUG,"num_printed=%d\n",numprinted);
                    //print_variable(vars->name, vars->name_length, vars);
                    if ((vars->type != SNMP_ENDOFMIBVIEW) &&
                        (vars->type != SNMP_NOSUCHOBJECT) &&
                        (vars->type != SNMP_NOSUCHINSTANCE)) {
                        /*
                         * not an exception value 
                         */
/*
                        if (check
                            && snmp_oid_compare(name, name_length,
                                                vars->name,
                                                vars->name_length) >= 0) {
                            fprintf(stderr, "Error: OID not increasing: ");
                            fprint_objid(stderr, name, name_length);
                            fprintf(stderr, " >= ");
                            fprint_objid(stderr, vars->name,
                                         vars->name_length);
                            fprintf(stderr, "\n");
                            running = 0;
                            exitval = 1;
                        }
*/
                        snmp_err_str[0]=0;
                        snprint_objid(snmp_err_str,SNMP_ERR_STR_SIZE-1,vars->name,vars->name_length);
                        snprint_value(buf, sizeof(buf)-5, vars->name, vars->name_length, vars);
                        
                        //print_log(LOG_DEBUG,"[Thread %u] '%s'='%s'\n",thread_id,snmp_err_str,buf);
                       
                        temp_string1=snmp_err_str;
                        size_t found;
                        found=temp_string1.find_last_of("."); 
                        temp_string2=temp_string1.substr(found+1);
                  
                        string search_string;
                        found=iter->first.find_last_not_of(".0123456789");
                        if(found==iter->first.npos){
                          //not found the search string is the whole thing!
                          search_string=iter->first;  
                        } 
                        else{
                          search_string=iter->first.substr(found);
                        }
                        search_string=iter->first.substr((iter->first.length()*2)/3);
                        string suffix_str;
                        //iterate over the data.
                        found=temp_string1.find(iter->first);
                        found=temp_string1.find(search_string);
                        print_log(LOG_DEBUG,"[Thread %u] [host %s] found=%u first=%s temp_string1=%s search_str=%s\n" , 
                              thread_id,ip_address.c_str(), found,iter->first.c_str(),temp_string1.c_str(),search_string.c_str());
                        if(temp_string1.npos!=found){
                           //print_log(LOG_INFO,"[Thread %u] [host %s] found!\n",thread_id,ip_address.c_str());
                           //suffix_str=temp_string1.substr(found+iter->first.length()+1); 
                           suffix_str=temp_string1.substr(found+search_string.length()+1);    
                           //print_log(LOG_INFO,"[Thread %u] found=%u first=%s temp_string1=%s\n" , thread_id,found,iter->first.c_str(),temp_string1.c_str());             
                           print_log(LOG_DEBUG,"[Thread %u] [host %s] found =%s!\n",thread_id,ip_address.c_str(),suffix_str.c_str());
                        }
                        else{
                           print_log(LOG_DEBUG,"[Thread %u] [host %s] NOT found!\n",thread_id,ip_address.c_str());
                           found=temp_string1.find_last_of(".");
                           suffix_str=temp_string1.substr(found+1);
                        }

                        
                        //print_log(LOG_DEBUG,"[Thread %u] index='%s'\n",thread_id,temp_string2.c_str());
                        uint64_t local_index;
                        local_index=atoll(temp_string2.c_str());

                        //printf("Raw Value = %s\n",buf);

                        temp_string2=extract_value_from_raw(buf);
                        //print_log(LOG_DEBUG,"[Thread %u] index=%lu value='%s' \n",thread_id,local_index,buf2);
                        //iter->second.indexof[temp_string2]=local_index;
                        //iter->second.valueof[local_index]=temp_string2; 
                        iter->second.suffix_of[temp_string2]=suffix_str;
                        iter->second.value_of[suffix_str]=temp_string2; 
                        print_log(LOG_DEBUG,"[Thread %u] [host %s] suffix_of[%s]='%s' \n",thread_id,ip_address.c_str(),temp_string2.c_str(),suffix_str.c_str());
                        

                        /*
                         * Check if last variable, and if so, save for next request.  
                         */
                        if (vars->next_variable == NULL) {
                            memmove(name, vars->name,
                                    vars->name_length * sizeof(oid));
                            name_length = vars->name_length;
                        }
                    } else {
                        /*
                         * an exception value, so stop 
                         */
                        running = 0;
                    }
                }
 

////////////////
                      }
                      else{
                        ///Error in response, report and exit loop
                        running=0;
                        snprintf(snmp_err_str,SNMP_ERR_STR_SIZE-1,"[Thread %u] Hostname: %-15s snmp_sync_response",thread_id, ip_address.c_str());
                        snmp_perror(snmp_err_str);

                      }
                      break;
                case STAT_TIMEOUT:
                        print_log(LOG_NOTICE,"[Thread %u] SNMP timeout(building table), host=%15s \n",thread_id, ip_address.c_str() );
                        running=0;
                      break;
                default:
                      //other error!
                         print_log(LOG_ERR,"SNMP MISC error\n");
                        running=0;
                      break;
            }
            if (response){
               snmp_free_pdu(response);
               response=NULL;
            }
            
            if(0==iter->second.suffix_of.size()){
              print_log(LOG_WARNING,"[Thread %u][host %s] no data inserted for %s\n",thread_id,ip_address.c_str(),iter->first.c_str());
              //fvalue=-1;
            }            

            //print_log(LOG_DEBUG,"[Thread %u] inserted %d values\n" ,thread_id,iter->second.indexof.size());
         
       }//end while

       if (response){
            snmp_free_pdu(response);
            response=NULL;
       }



       //is this the best place to clse it?
       snmp_sess_close(sp);
 
    }//end for
    return fvalue;
}
Esempio n. 27
0
bool stage::initShaders() {
    //Link Shaders
    GLint link_ok = GL_FALSE;
    
    GLuint vs, fs;
    if ((vs = create_shader((const char*)config::vert_shader_path.string().c_str(), GL_VERTEX_SHADER))   == 0) return 0;
    if ((fs = create_shader((const char*)config::frag_shader_path.string().c_str(), GL_FRAGMENT_SHADER)) == 0) return 0;
    
    //Create Program and Attach Shaders
    shader_program = glCreateProgram();
    glAttachShader(shader_program, vs);
    glAttachShader(shader_program, fs);


    //Bind Attributes
    glBindAttribLocation(shader_program, attribute_coord3d, config::coord3d.c_str());
    glBindAttribLocation(shader_program, attribute_vertex_uv, config::vertex_uv.c_str());
    glBindAttribLocation(shader_program, attribute_vertex_normal, config::vertex_normal.c_str());
    glBindAttribLocation(shader_program, attribute_model, config::model_matrix.c_str());

    
    //Link Shader
    glLinkProgram(shader_program);
    glGetProgramiv(shader_program, GL_LINK_STATUS, &link_ok);
    if (!link_ok) {
        fprintf(stderr, "glLinkProgram:");
        print_log(shader_program);
        return 0;
    }
    
    //Check Attributes
    if (glGetAttribLocation(shader_program,config::coord3d.c_str()) == -1) {
        fprintf(stderr, "Could not bind attribute %s\n", config::coord3d.c_str());
        return 0;
    }
    /*if (glGetAttribLocation(shader_program,config::v_color.c_str()) == -1) {
        fprintf(stderr, "Could not bind attribute %s\n", config::v_color.c_str());
        return 0;
    }*/
    if (glGetAttribLocation(shader_program,config::vertex_uv.c_str()) == -1) {
        fprintf(stderr, "Could not bind attribute %s\n", config::vertex_uv.c_str());
        return 0;
    }
    if (glGetAttribLocation(shader_program,config::vertex_normal.c_str()) == -1) {
        fprintf(stderr, "Could not bind attribute %s\n", config::vertex_normal.c_str());
        return 0;
    }
    if (glGetAttribLocation(shader_program,config::model_matrix.c_str()) == -1) {
        fprintf(stderr, "Could not bind attribute %s\n", config::model_matrix.c_str());
        return 0;
    }
    
    //Get Uniform Locations
    uniform_view = glGetUniformLocation(shader_program, config::view_matrix.c_str());
    if (uniform_view == -1) {
        fprintf(stderr, "Could not bind uniform %s\n", config::view_matrix.c_str());
        return 0;
    }

    uniform_proj = glGetUniformLocation(shader_program, config::proj_matrix.c_str());
    if (uniform_proj == -1) {
        fprintf(stderr, "Could not bind uniform %s\n", config::proj_matrix.c_str());
        return 0;
    }
    
    uniform_texture = glGetUniformLocation(shader_program, config::texture_sampler.c_str());
    if (uniform_texture == -1) {
        fprintf(stderr, "Could not bind uniform %s\n", config::texture_sampler.c_str());
        return 0;
    }
    
    uniform_lightPos = glGetUniformLocation(shader_program, config::light_pos.c_str());
    if (uniform_lightPos == -1) {
        fprintf(stderr, "Could not bind uniform %s\n", config::light_pos.c_str());
        return 0;
    }
    
    uniform_alpha = glGetUniformLocation(shader_program, config::alpha_chn.c_str());
    if (uniform_alpha == -1) {
        fprintf(stderr, "Could not bind uniform %s\n", config::alpha_chn.c_str());
        return 0;
    }
    
    return 1;
}
Esempio n. 28
0
string Host_Info::extract_value_from_raw(string raw){
   char pattern[]="[^:]+:\\s*\"?([^\"]*)\"?";
   static pcre *re=NULL;
   const char *error;
   int erroffset;
   static pthread_mutex_t re_lock = PTHREAD_MUTEX_INITIALIZER;
   int rvalue;

   //for the actual execution!
   char check_string[STD_STRING_SIZE];
   int ovector[PCRE_EXEC_OVECCOUNT_2];
   int rc;
   char *value;
   char empty_string[]="";
   string out_string;

   value=empty_string;   

   rvalue=pthread_mutex_lock(&re_lock);
   assert(0==rvalue);

   if(NULL==re){
      re = pcre_compile(
              pattern,          /* the pattern */
              0,                /* default options */
              &error,           /* for error message */
              &erroffset,       /* for error offset */
              NULL);            /* use default character tables */
      assert(NULL!=re);
   }
   rvalue=pthread_mutex_unlock(&re_lock);   
   assert(0==rvalue);

   assert(NULL!=re);
   bzero(check_string,STD_STRING_SIZE);
   strncpy(check_string,raw.c_str(),STD_STRING_SIZE-1);
   rc = pcre_exec(
           re,                   //result of pcre_compile() 
           NULL,                 // The studied the pattern 
           check_string,         // the subject string
           #if defined _GNU_SOURCE || _POSIX_C_SOURCE >= 200809L 
           strnlen(check_string,STD_STRING_SIZE), // the length of the subject string
           #else
           strlen(check_string),
           #endif 
           0,                    // start at offset 0 in the subject 
           0,                    // default options 
           ovector,              // vector of integers for substring information 
           PCRE_EXEC_OVECCOUNT_2); // number of elements (NOT size in bytes) 
    if(rc>=1 && ovector[2]!=-1){ 
       //we at least one match!
       value=check_string;
       value+=ovector[2]; 
       out_string=value;
    }
    if('"'==out_string[out_string.length()-1]){
      out_string.resize(out_string.length()-1);
    }
    print_log(LOG_DEBUG,"Value_extractor Raw='%s' value='%s'\n",check_string,out_string.c_str());
    return out_string;


}
Esempio n. 29
0
/**
 * The main function of BaseStation for Mongol.
 *
 * Entry point of program. Upon starting with normal mode values set,
 * this function parses any command line arguments, initializes the controller
 * interface (\sa Controller.h), intitializes the robot communication interface
 * (\sa Serial.h), and then enters the main control loop of the program. There,
 * the program basically gathers user input data from the controller, builds a
 * serial packet, and then sends it to the robot. The program waits for
 * confirmation from the robot in the form of a PKT_RDY packet type before
 * looping again.
 */
int
main (int argc, char* argv[])
{
    // Set default values
    m_ctrl_mode = Ctrl_Mode_Keyboard;
    m_comm_mode = Comm_Mode_Offline;
    m_ui_mode   = UI_Mode_Terminal;

    // Parse command line arguements
    parse_args (argc, argv);

    // Initialize SDL (VIDEO flag also initializes event handling)
    print_log ("Initializing controller... ", Log_Level_Med);
    if (!(initCtrl()))
    {
        print_log ("Controller failed to intialize.\n", Log_Level_High);
        quit_basestation ();
    }
    print_log ("Controller Initialized.\n", Log_Level_Med);

    // Initialize serial port (includes looking for HELLO packet
    // If not port name specified, default to /dev/ttyUSB0 (for Linux)
    if (m_comm_mode == Comm_Mode_Online)
    {
        print_log ("Connecting to robot... ", Log_Level_Med);
        if ((ms_comm_device ? init_serial (ms_comm_device) : init_serial ("/dev/ttyUSB0")) < 0)
        {
            print_log ("Failed to connect\n", Log_Level_High);
            m_comm_mode = Comm_Mode_Offline;
            quit_basestation ();
        }
        print_log ("Robot connected.\n", Log_Level_Med);
    }

    Msg out_msg;
    Msg in_msg;
    char intype_buf [128];
    char outtype_buf [128];
    int print_nxt_received = 0;

    // Main program loop
    for(;;)
    {
        next_event (&out_msg);

        if(m_comm_mode == Comm_Mode_Online)
        {
            do
            {
                serial_write (&out_msg);
                usleep (10);
            }
            while (serial_read (&in_msg) ||
                   (in_msg.type != Msg_Type_Ready));

            if (out_msg.type != Msg_Type_Standby)
            {
                type_to_str (intype_buf, out_msg.type);
                printf ("Sent: %s\n", intype_buf);
                type_to_str (outtype_buf, in_msg.type);
                printf ("Received: %s\n", outtype_buf);
            }
        }
    }

    return 0;
}
int put_ts_packet(int no, unsigned char* packet, int sz) {
    unsigned char* p;
    int transport_error_indicator, pid, payload_unit_start_indicator, continuity_counter, last_continuity_counter;
    int i; // e = 0
    if((sz % 188)) {
        //e = 1;
        print_log("L : %d", sz);
        //print_log("Video %d Invalid size: %d\n", no, sz);
    } else {
        for(i = 0; i < sz; i += 188) {
            p = packet + i;

            pid = ((p[1] & 0x1f) << 8) + p[2];

            demux[no].ts_packet_c++;
            if(!is_sync(packet + i)) {
                //e = 1;
                print_log("S     ");
                demux[no].sync_err++;
                if(0x80==(p[1] & 0x80))
                    demux[no].sync_err_set++;
                print_log("0x%x, 0x%x, 0x%x, 0x%x \n", *p, *(p+1),  *(p+2), *(p+3));
                //print_log("   Video %d Invalid sync: 0x%02x, Offset: %d, Frame No: %d\n", no, *(packet + i), i, i / 188);
                //break;
                continue;
            }

            // Error Indicator가 설정되면 Packet을 버림
            transport_error_indicator = (p[1] & 0x80) >> 7;
            if(1 == transport_error_indicator) {
                demux[no].malformed_packet_c++;
                //e++;
                //print_log("I      ");
                //print_log("   Video %d PID 0x%04x: err_ind, Offset: %d, Frame No: %d\n", no, pid, i, i / 188);
                continue;
            }

            payload_unit_start_indicator = (p[1] & 0x40) >> 6;

            demux[no].pids[pid].count++;

            // Continuity Counter Check
            continuity_counter = p[3] & 0x0f;

            if(demux[no].pids[pid].continuity == -1) {
                demux[no].pids[pid].continuity = continuity_counter;
            } else {
                last_continuity_counter = demux[no].pids[pid].continuity;

                demux[no].pids[pid].continuity = continuity_counter;

                if(((last_continuity_counter + 1) & 0x0f) != continuity_counter) {
                    demux[no].pids[pid].discontinuity++;
                    //e++;
                    //print_log("D      ");
                    //print_log("   Video %d PID 0x%04x: last counter %x ,current %x, Offset: %d,Frame No: %d, start_ind: %d\n", no, pid, last_continuity_counter, continuity_counter, i, i / 188, payload_unit_start_indicator);
                }
            }
        }
    }

    //if(e) {
    //    print_log("Video %d Received Size: %d, Frame Count: %d, Error Count: %d\n", no, sz, sz / 188, e);
    //}
    return 0;
}