コード例 #1
0
ファイル: lbapp.cpp プロジェクト: shengang1006/xxc2hd
//�������Ͽ�
int lbapp::on_close(app_connection *n, int reason){
	server_s * s = (server_s*)n->get_context();
	if(!s){
		return -1;
	}
	
	if(s->type == devmgr_type){
		svr_hash::instance_devmgr()->destory_node(s->identify, s->weight);
	}
	else if(s->type == cntmgr_type){
		svr_hash::instance_cntmgr()->destory_node(s->identify, s->weight);
	}
	
	log_out(log_error, "svr_disconnect::%s reason %d\n", s->identify, reason);
	
	delete s;
	
	return 0;
}
コード例 #2
0
ファイル: svrapp.cpp プロジェクト: shengang1006/xxc2hd
//上下线通知
int svrapp::alarm_notify(param_list * pl){
	
	cJSON * jsdev = cJSON_GetObjectItem(pl->jsdata, "devkey");
	cJSON * jscpy = cJSON_GetObjectItem(pl->jsdata, "company_id");
	cJSON * jstyp = cJSON_GetObjectItem(pl->jsdata, "type");
	server_info * sif = (server_info*)pl->n->get_context();

	if(!jsdev  || jsdev->type != cJSON_String ||
		!jscpy || jscpy->type != cJSON_Number ||
		!jstyp || jstyp->type != cJSON_String){
		log_out(log_error, "alarm_notify::invalid json %s\n", pl->content);
		return -1;
	}
	
	int state = strcmp(jstyp->valuestring, offline_alarm) ? em_online: em_offline;
    
    return update_device(jsdev->valuestring, jscpy->valueuint64, (uint)time(NULL), 
    state, sif->get_numkey());
}
コード例 #3
0
ファイル: baseapp.cpp プロジェクト: shengang1006/xxc2hd
int baseapp::alarm_notify(param_list * pl){
	
	cJSON * jsdev = cJSON_GetObjectItem(pl->jsdata, "device_id");
	cJSON * jscpy = cJSON_GetObjectItem(pl->jsdata, "company_id");
	cJSON * jstyp = cJSON_GetObjectItem(pl->jsdata, "type");
	
	if(!jsdev || jsdev->type != cJSON_Number ||
		!jscpy || jscpy->type != cJSON_Number ||
		!jstyp || jstyp->type != cJSON_String){
		log_out(log_error, "alarm_notify::invalid json %s\n", pl->content);
		return -1;
	}
	
	uint cpy = jscpy->valueuint;
	uint dev = jsdev->valueuint;
	int state = strcmp(jstyp->valuestring, offline_alarm) ? em_online: em_offline;
	update_device(dev, cpy, state, pl->n);
	return 0;
}
コード例 #4
0
ファイル: lbapp.cpp プロジェクト: shengang1006/xxc2hd
//{"data":{"server":"127.0.0.1:29025"},"code":0,"message":"succ"}
int lbapp::get_dev_info(const char * sn, device_s & ds){
    
	char url[512] = {0};
	sprintf(url, "%s%s", m_devapi, sn);

	char buf[512] = {0};
	if(get_http_request(url, buf, sizeof(buf) -1) < 0){
		return -1;
	}

	cJSON * json = cJSON_Parse(buf);
	if(!json){
		return -1;
	}

	cJSON * jscod  = cJSON_GetObjectItem(json, "code");
	cJSON * jsdsc  = cJSON_GetObjectItem(json, "message");
	cJSON * jsdta  = cJSON_GetObjectItem(json, "data");

	if(!jscod || !jsdsc ||!jsdta){
		cJSON_Delete(json);
		log_out(log_debug, "get_dev_info::invalid json\n");
		return -1;
	}

	if(jscod->valueint){
		cJSON_Delete(json);
		return -1;
	}

	cJSON * jssvr  = cJSON_GetObjectItem(jsdta, "server");
	if(!jssvr || jssvr->type != cJSON_String){
		cJSON_Delete(json);
		return -1;
	}

	memset(&ds, 0, sizeof(ds));
	strncpy(ds.mgr, jssvr->valuestring, sizeof(ds.mgr));

	cJSON_Delete(json);
	return 0;
}
コード例 #5
0
ファイル: svrapp.cpp プロジェクト: shengang1006/xxc2hd
int svrapp::poll_alarm(){
	
	std::map<strkey_t, device_s> & temp = m_devmap[m_group_index];
	std::map<strkey_t, device_s>::iterator it = temp.begin();
	uint now = (uint)time(NULL);

	//poll device
	while(it != temp.end()){
		
		device_s & info = it->second;	
	
		if (info.state != em_offline ){ 	
			it++;
			continue;
		}

		uint now_secs = alram_rule_secs[info.alram_rule_index] + m_alarm_threshold;
		if(info.off_tm + now_secs > now){
			it++;
			continue;
		}

		//计算下线时间
		uint off_tml = now - info.off_tm;
		alarm_event(it->first.c_str(), info.company_id, info.off_tm, off_tml, em_offline);
			
		//触发告警
		if(++info.alram_rule_index >= sizeof(alram_rule_secs)/sizeof(alram_rule_secs[0])){
			log_out(log_error, "poll_alarm::expire delete device(%s) company(%lu)!\n", 
            it->first.c_str(), info.company_id);
			temp.erase(it++);
		}
		else{
			it++;
		}
	}

	if(++m_group_index >= max_group_count){
		m_group_index = 0;
	}
	return 0;
}
コード例 #6
0
ファイル: baseapp.cpp プロジェクト: shengang1006/xxc2hd
int baseapp::mgr_disconnect(app_connection *n, int reason){
	server_info * s = (server_info*)n->get_context();
	ipaddr & peer = n->get_peeraddr();

	std::map<uint, app_connection*>::iterator it = m_devmap.begin();
	while(it != m_devmap.end()){
		server_info * s1 = (server_info*)it->second->get_context();
		if (s1->get_id() == s->get_id()){
			m_devmap.erase(it++);
		}
		else{
			it++;
		}
	}
	m_svrmap.erase(s->get_id());

	log_out(log_warn, "mgr_disconnect::server %s:%d reason %d\n", peer.ip, peer.port, reason);
	post_connect(peer.ip, peer.port, s->get_interval(), s);
	return 0;
}
コード例 #7
0
ファイル: svrapp.cpp プロジェクト: shengang1006/xxc2hd
int svrapp::login_mgr_req(app_connection *n){

	ipaddr & peer = n->get_peeraddr();
	server_info * sif = (server_info*)n->get_context();
	m_svrmap[sif->get_numkey()] = n;
	sif->reset_interval();
	
	const char *token = "\"token\":\"motiondetect\"";
	
	char event_list[256] = {0};
	sprintf(event_list, "\"event_list\":[\"%s\"]", motion_detect_alarm);
	
	char identify[512] = {0};
	sprintf(identify, "{%s,%s}", token, event_list);
	
	post_req(n, client_login_mgr_req, identify);

	log_out(log_debug, "login_mgr_req::to(%s:%d) %s\n", peer.ip, peer.port, identify);
	return 0;
}
コード例 #8
0
ファイル: svrapp.cpp プロジェクト: shengang1006/xxc2hd
int svrapp::alarm_event(const char * dev_idkey, uint64 cpy, uint offtm, 
						uint offtmlong, uint state ){
	
	char buf[256] = {0};
	
    uint64 dev = 0;
    uint ptm = 0;
    
    parse_devkey(ptm, dev, dev_idkey);
    
	sprintf(buf, 
	"{\"platform\":%u,\"device_id\":%lu,\"company_id\":%lu,\"off_tm\":%u,\"off_tml\":%u,\"state\":%u}",
    ptm, dev, cpy, offtm, offtmlong, state);

	m_http_post.push(buf, strlen(buf));
	
	log_out(log_warn, "alarm_event: %s\n", buf);
	
	return 0;
}
コード例 #9
0
ファイル: baseapp.cpp プロジェクト: shengang1006/xxc2hd
int baseapp::connect_mgr_ok(const char * cfg, const char * name, app_connection *n){

	ipaddr & peer = n->get_peeraddr();
	server_info * s = (server_info*)n->get_context();
	m_svrmap[s->get_id()] = n;
	s->reset_interval();
	
	char events[256]   = {0};
	sprintf(events, "\"event\":[\"%s\",\"%s\"]", online_alarm, offline_alarm);
	
	char companys[512] = {0};
	read_companys(cfg, "company", companys);
	
	char identify[512] = {0};
	sprintf(identify, "{\"token\":\"%s\",%s,\"company\":%s}", name, events, companys);
	
	post_req(n, client_login_mgr_req, identify);

	log_out(log_debug, "connect ok %s:%d login mgr %s\n", peer.ip, peer.port, identify);
	return 0;
}
コード例 #10
0
ファイル: httppost.cpp プロジェクト: shengang1006/xxc2hd
int http_post::init(const char * api, const char * key /*= NULL*/){

	if(m_ring_buf.create(10000) <0){
		return -1;
	}

	
	if(key){
		memset(m_key, 0, sizeof(m_key));
		strncpy(m_key, key, sizeof(m_key) -1);
	}

	memset(m_api, 0, sizeof(m_api));
	strncpy(m_api, api, sizeof(m_api));

	if(create_thread(NULL, push_task, "push_task", this) <0){
		return -1;
	}

	log_out(log_debug, "init::init ok api(%s) key(%s)\n", m_api, key);
	return 0;
}
コード例 #11
0
ファイル: client.c プロジェクト: bachnxhedspi/Basic-chess
int menu(int sockfd){

	char choose[2];
	char aaa[1];
	int max_user_list;
	struct pollfd server[2];
	int rv,i,t;
	char mesg[LEN];
	User_List user_list[100];
	User_List play_list[1];

	while(1){
		t = wait(sockfd,play_list);
		if (t == 1){
			blwh=-1;//Quan den
			khoitaoboard();
			playing(sockfd,play_list);
		}else if(t ==0){
			printf("\n***MENU CHINH***\n");
			printf("\n1.Chon 1 user dang online de choi cung");
			printf("\n2.Thoat");
			printf("\nBan chon: ");
	    	fgets(choose,3,stdin);
	    	switch(choose[0]){
	    		case '1' :
	    			blwh=1; //Quan trang
	    			khoitaoboard();
	    			choose_user(sockfd,play_list);
	    			break;
	    		case '2' :
	    			log_out(sockfd);
	    			return 1;
	    		default :
	    			break;	    			
	    	}

		}
	}
}
コード例 #12
0
ファイル: offlineapp.cpp プロジェクト: shengang1006/xxc2hd
int svrapp::login_mgr_req(app_connection *n){

	ipaddr & peer = n->get_peeraddr();
	server_info * s = (server_info*)n->get_context();
	m_svrmap[s->get_id()] = n;
	s->reset_interval();
	
	const char *token = "\"token\":\"offline alarm server\"";
	
	char events[256] = {0};
	sprintf(events, "\"event\":[\"%s\",\"%s\"]", online_alarm, offline_alarm);
	
	char companys[512] = {0};
	read_companys(ulu_c2hd_offline_conf, "company", companys);
	
	char identify[512] = {0};
	sprintf(identify, "{%s,%s,\"company\":%s}", token, events, companys);
	
	post_req(n, client_login_mgr_req, identify);

	log_out(log_debug, "login_mgr_req::to(%s:%d) %s\n", peer.ip, peer.port, identify);
	return 0;
}
コード例 #13
0
ファイル: svrapp.cpp プロジェクト: shengang1006/xxc2hd
int svrapp::mgr_disconnect(app_connection *n, int reason){

	server_info * sif = (server_info*)n->get_context();
	ipaddr & peer = n->get_peeraddr();

	uint now = (uint)time(NULL);
	for(int index = 0; index < max_group_count; index++){
		std::map<strkey_t, device_s> & temp = m_devmap[index];
		std::map<strkey_t, device_s>::iterator it = temp.begin();
		for(; it != temp.end(); it++){
			if (it->second.svr_numkey == sif->get_numkey()){
				it->second.state = em_offline; 
				it->second.off_tm = now;
				it->second.off_times++;
			}
		}
	}
    
	m_svrmap.erase(sif->get_numkey());
	log_out(log_warn, "mgr_disconnect::server(%s) reason(%d)\n", peer.ip, reason);
	post_connect(peer.ip, peer.port, sif->get_interval(), sif);
	return 0;
}
コード例 #14
0
ファイル: upgradeapp.cpp プロジェクト: shengang1006/xxc2hd
int upgradeapp::connect_server(const char * cfg, const char * section, int type){

	char identify[128] = {0};
	int count = 0;
	char ** devmgr = GetIniItemTable(cfg, section, count);
	for(int i = 0; i < count; i++){

		memset(identify, 0, sizeof(identify));
		sscanf(devmgr[i], "server %s", identify);

		char * pt = strchr(identify, ':');
		if(!pt){
			continue;
		}

		char host[128] = {0};
		strncpy(host, identify, pt - identify);

		struct hostent * h = gethostbyname(host);
		if(!h){
			continue;
		}

		ipaddr devip = {{0}, 0};
		strncpy(devip.ip, inet_ntoa(*((struct in_addr *)h->h_addr)), sizeof(devip.ip));
		devip.port = atoi(pt+1);

		server_info * s = new server_info(type);
		post_connect(devip.ip, devip.port, 2000, s);

		free(devmgr[i]);
		log_out(log_debug, "connect_server::%s identify(%s) ip(%s) id(%d)\n", cfg, identify, 
				devip.ip, s->get_id());
	}
	free(devmgr);
	return 0;
}
コード例 #15
0
ファイル: upgradeapp.cpp プロジェクト: shengang1006/xxc2hd
//�ƻ���ѵ
int upgradeapp::plan_poll(){

	char buf[256 * 10] = {0};
	char * pos = buf;
	int total_count = m_devmap.size() ;
	int sent_count = 0;
	int per_count = 10;
	bool init = false;
	log_out(log_debug, "plan_poll:device count(%d)\n", total_count);

	std::map<uint, dev_state>::iterator it = m_devmap.begin();
	do{
		if(!init){
			memset(buf, 0, sizeof(buf));
			pos = buf;
			sprintf(pos, "msg={\"platform\":\"device\",\"data\":[");
			pos = pos + strlen(pos);
			init = true;
		}

		uint device_id = it->first;
		dev_state * ds = &(it++)->second;

	//	if(!ds->version.empty() && (ds->upgrade_state != e_upgrading) &&
	//			ds->line_state == em_online && !ds->package.empty()){
		if(!ds->version.empty() && (ds->upgrade_state != e_upgrading) &&
				ds->line_state == em_online){

			char item[256] = {0};
			sprintf(item, "{\"device_id\":%u,\"version\":\"%s\",\"devsn\":\"%s\",\"ulusn\":\"%s\"},", device_id,
					(ds->version).c_str(), (ds->devsn).c_str(), (ds->ulusn).c_str());
			strcpy(pos, item);
			pos += strlen(item);	
			sent_count++;
		}

		if(sent_count >= per_count || it == m_devmap.end()){
			if(*(pos-1) == ','){
				pos--;
			}
			*pos++ = ']';
			*pos++ = '}';
			if(sent_count == 0){
				log_out(log_debug, "plan_poll: no device need upgrade\n");
				break;
			}
			sent_count = 0;
			init = false;
			log_out(log_debug,"plan_poll::sent %s\n", buf);
			char result[128 * 128] = {0};
			if(post(m_api_upgrade, buf, pos - buf, result, sizeof(result)) < 0){
				log_out(log_error, "plan_poll:post fail\n");	
			}
			else{
				device_update_data(result, strlen(result));
			}
		}


	}while(it != m_devmap.end());

	return 0;
}
コード例 #16
0
ファイル: upgradeapp.cpp プロジェクト: shengang1006/xxc2hd
int upgradeapp::get_device_version_ackx(param_list * pl){
	log_out(log_debug, "get_device_version_ackx::%s\n", pl->content);

	cJSON * jserror = cJSON_GetObjectItem(pl->json, "error");
	cJSON * jsversion = cJSON_GetObjectItem(pl->jsdata, "version");
	cJSON * jsid = cJSON_GetObjectItem(pl->jsdata, "device_id");
//	cJSON * jspackage = cJSON_GetObjectItem(pl->jsdata, "package");
	cJSON * jsdevsn = cJSON_GetObjectItem(pl->jsdata, "devsn");
	cJSON * jsulusn = cJSON_GetObjectItem(pl->jsdata, "ulusn");

	if(!jserror || jserror->type != cJSON_Number || 
			!jsversion || jsversion->type != cJSON_String ||
			!jsid || jsid->type != cJSON_Number ||
		//	!jspackage || jspackage->type != cJSON_String ||
			!jsdevsn || jsdevsn->type != cJSON_String ||
			!jsulusn || jsulusn->type != cJSON_String){
		log_out(log_error, "get_device_version_ack::invalid json %s\n", pl->content);
		return -1;
	}

	if(jserror->valueint){
		log_out(log_error, "get_device_version_ack::error %u\n", jserror->valueint);
		return -1;
	}

	char * version = jsversion->valuestring;
	uint id = jsid->valueuint;

	std::map<uint, dev_state>::iterator it = m_devmap.find(id);
	if(it == m_devmap.end()){
		log_out(log_error, "get_device_version_ack::invalid device_id %u\n", id);
		return 0;
	}

	if(it->second.upgrade_state == e_upgrading){

		char buf[512] = {0};
		int state = e_upgradesucc;
		if(it->second.version == version){
			state = e_upgradefail;
		}
		else{
			//state = e_upgradesucc;
			it->second.version =version;
		//	it->second.package = jspackage->valuestring;
			it->second.devsn = jsdevsn->valuestring;
			it->second.ulusn = jsulusn->valuestring;
		}
		it->second.upgrade_state = state;

		sprintf(buf, "msg={\"platform\":\"device\",\"data\":[{\"device_id\":%u,\"version_id\":%u,\"status\":%d}]}", 
				it->first, it->second.version_id, state);

		log_out(log_debug, "get_device_version_ackx: %s\n", buf);

		char result[128 * 128] = {0};
		if(post(m_api_upgrade_status, buf, strlen(buf), result, sizeof(result)) < 0){
			log_out(log_error, "get_device_version_ackx:post fail\n");	
		}
		else{
			log_out(log_debug, "get_device_version_ackx:rev data %s\n", result);
		}
	}
	else{
		it->second.version = version;
	//	it->second.package = jspackage->valuestring;
		it->second.devsn = jsdevsn->valuestring;
		it->second.ulusn = jsulusn->valuestring;
	}
	return 0;
}
コード例 #17
0
ファイル: upgradeapp.cpp プロジェクト: shengang1006/xxc2hd
int upgradeapp::login_mgr_ack(param_list * pl){

	log_out(log_debug, "login_mgr_ack::%s\n", pl->content);
	post_req(pl->n, get_online_device_req);
	return 0;
}
コード例 #18
0
ファイル: util.c プロジェクト: djwong/e2fsprogs
int ask_yn(e2fsck_t ctx, const char * string, int def)
{
	int		c;
	const char	*defstr;
	const char	*short_yes = _("yY");
	const char	*short_no = _("nN");
	const char	*short_yesall = _("aA");
	const char	*english_yes = "yY";
	const char	*english_no = "nN";
	const char	*english_yesall = "aA";
	const char	*yesall_prompt = _(" ('a' enables 'yes' to all) ");
	const char	*extra_prompt = "";
	static int	yes_answers;

#ifdef HAVE_TERMIOS_H
	struct termios	termios = {0, }, tmp;

	tcgetattr (0, &termios);
	tmp = termios;
	tmp.c_lflag &= ~(ICANON | ECHO);
	tmp.c_cc[VMIN] = 1;
	tmp.c_cc[VTIME] = 0;
	tcsetattr (0, TCSANOW, &tmp);
#endif

	if (def == 1)
		defstr = _(_("<y>"));
	else if (def == 0)
		defstr = _(_("<n>"));
	else
		defstr = _(" (y/n)");
	/*
	 * If the user presses 'y' more than 8 (but less than 12) times in
	 * succession without pressing anything else, display a hint about
	 * yes-to-all mode.
	 */
	if (yes_answers > 12)
		yes_answers = -1;
	else if (yes_answers > 8)
		extra_prompt = yesall_prompt;
	log_out(ctx, "%s%s%s? ", string, extra_prompt, defstr);
	while (1) {
		fflush (stdout);
		if ((c = read_a_char()) == EOF)
			break;
		if (c == 3) {
#ifdef HAVE_TERMIOS_H
			tcsetattr (0, TCSANOW, &termios);
#endif
			if (ctx->flags & E2F_FLAG_SETJMP_OK) {
				log_out(ctx, "\n");
				longjmp(e2fsck_global_ctx->abort_loc, 1);
			}
			log_out(ctx, "%s", _("cancelled!\n"));
			yes_answers = 0;
			return 0;
		}
		if (strchr(short_yes, (char) c)) {
		do_yes:
			def = 1;
			if (yes_answers >= 0)
				yes_answers++;
			break;
		} else if (strchr(short_no, (char) c)) {
		do_no:
			def = 0;
			yes_answers = -1;
			break;
		} else if (strchr(short_yesall, (char)c)) {
		do_all:
			def = 2;
			yes_answers = -1;
			ctx->options |= E2F_OPT_YES;
			break;
		} else if (strchr(english_yes, (char) c)) {
			goto do_yes;
		} else if (strchr(english_no, (char) c)) {
			goto do_no;
		} else if (strchr(english_yesall, (char) c)) {
			goto do_all;
		} else if ((c == 27 || c == ' ' || c == '\n') && (def != -1)) {
			yes_answers = -1;
			break;
		}
	}
	if (def == 2)
		log_out(ctx, "%s", _("yes to all\n"));
	else if (def)
		log_out(ctx, "%s", _("yes\n"));
	else
		log_out(ctx, "%s", _("no\n"));
#ifdef HAVE_TERMIOS_H
	tcsetattr (0, TCSANOW, &termios);
#endif
	return def;
}
コード例 #19
0
ファイル: svrapp.cpp プロジェクト: shengang1006/xxc2hd
int svrapp::alarm_notify(param_list * pl){
	
	cJSON * jstyp = cJSON_GetObjectItem(pl->jsdata, "type");
    cJSON * jscpy = cJSON_GetObjectItem(pl->jsdata, "company_id");
	cJSON * jsdev = cJSON_GetObjectItem(pl->jsdata, "devkey");
	cJSON * jstme = cJSON_GetObjectItem(pl->jsdata, "time");
    cJSON * jschn = cJSON_GetObjectItem(pl->jsdata, "channel");
    cJSON * jsnme = cJSON_GetObjectItem(pl->jsdata, "image_name");
	cJSON * jssze = cJSON_GetObjectItem(pl->jsdata, "image_size");
	cJSON * jscsp = cJSON_GetObjectItem(pl->jsdata, "cloud_storage_path");
	cJSON * jscst = cJSON_GetObjectItem(pl->jsdata, "cloud_storage_type");
	cJSON * jsust = cJSON_GetObjectItem(pl->jsdata, "upload_start_time");
	cJSON * jsuet = cJSON_GetObjectItem(pl->jsdata, "upload_end_time");
    
    if(!jstyp || jstyp->type != cJSON_String ||
       !jsdev || jsdev->type != cJSON_String ||
	   !jstme || jstme->type != cJSON_Number ||
	   !jscpy || jscpy->type != cJSON_Number ||
       !jschn || jschn->type != cJSON_Number ||
       !jsnme || jsnme->type != cJSON_String ||
	   !jssze || jssze->type != cJSON_Number ||
	   !jscsp || jscsp->type != cJSON_String ||
	   !jscst || jscst->type != cJSON_Number ||
	   !jsust || jsust->type != cJSON_Number ||
	   !jsuet || jsuet->type != cJSON_Number){
           log_out(log_error, "alarm_notify::invalid alarm type %s\n", pl->content);
		   return -1;
	}
  
    char chnkey[strkey_len] = {0};
    create_chnkey(jsdev->valuestring, jschn->valueuint, chnkey);
    int index = hash_key(jscpy->valueuint64, max_group_count);
	std::map<strkey_t, motiondetect_s> & temp = m_alarmmap[index];
	std::map<strkey_t, motiondetect_s>::iterator it = temp.find(chnkey);
    
    if(it == temp.end()){
		motiondetect_s mdts = {0};
        mdts.state = alarm_ok;
		it = temp.insert(std::make_pair(chnkey, mdts)).first;
	}

	motiondetect_s &mdts = it->second;
	mdts.time = jstme->valueuint;	
	mdts.company_id  = jscpy->valueuint64;
 	mdts.state = alarm_have;
     
    strncpy(mdts.image_name, jsnme->valuestring, sizeof(mdts.image_name));
	strncpy(mdts.cloud_storage_path, jscsp->valuestring, sizeof(mdts.cloud_storage_path));
	mdts.image_size = jssze->valueuint;
	mdts.cloud_storage_type = jscst->valueuint;
	mdts.upload_start_time = jsust->valueuint;
	mdts.upload_end_time = jsuet->valueuint;
    
    uint cur_time =  (uint)time(NULL);
	if(cur_time - mdts.last_alarm_time > (uint)m_alarm_threshold){
		alarm_event(chnkey, mdts);
	}
	mdts.last_alarm_time = cur_time;
    
    return 0;
}
コード例 #20
0
ファイル: main.c プロジェクト: Roulattice/Roulattice
int main(int argc, char **argv) {
    
    /* the times recorded are: 
     start of programm, start of chain generation,
     end of chain generation, end of programm */
    double time[4];
    time[0] = time_of_day();
    
    
    //-----------------------------------------------------------------------------------------------------------------------------------------------
    //-----------------------------------------------------------------------------------------------------------------------------------------------
    // open all neccessary files
    
    // general output file, contains basically everything which was written to the terminal
    FILE * output_file;
    output_file = fopen("output_file.dat", "w+");
    
    FILE * conv_obs_file;
    conv_obs_file = fopen("convergence_obs.dat", "w+");
    
    // pair correlation function can be weighted with potentials
    FILE * pair_correl_file;
    pair_correl_file = fopen("pair_correlation_function.dat", "w+");
    
    //------------------------------------------------------------------------------
    // all files connected to intramolecular interactions

    FILE * intra_pot_file;
    intra_pot_file = fopen("intramolecular_obs.dat", "w+");
    
    FILE * intra_boltzman_factors_hist;
    intra_boltzman_factors_hist = fopen("intramolecular_factors_hist.dat", "w+");
    
    FILE * intra_interactions_file;
    intra_interactions_file = fopen("intramolecular_interactions_hist.dat", "w+");
    
 //   FILE * intra_interactions_testfile;
 //   intra_interactions_testfile = fopen("intramolecular_interactions_testhist.dat", "w+");
    
    FILE * convergence_intraweights;
    convergence_intraweights = fopen("intramolecular_convergence_Z.dat", "w+");
    fprintf(convergence_intraweights, "### convergence_point -- sum-of-boltzman-factors \n");
    
    FILE * conv_intraobs_file;
    conv_intraobs_file = fopen("intramolecular_convergence_obs.dat", "w+");

    
    //-----------------------------------------------------------------------------------------------------------------------------------------------
    //-----------------------------------------------------------------------------------------------------------------------------------------------
    // input and first output
    
    
    // hello message of the programm, always displayed!
    
    log_out(output_file, "\n-----------------------------------------------------------------------------------\n");
    log_out(output_file, "Roulattice version 1.1, Copyright (C) 2015 Johannes Dietschreit\n");
    log_out(output_file, "This program comes with ABSOLUTELY NO WARRANTY; for version details type '-info'.\n");
    log_out(output_file, "This is free software, and you are welcome to redistribute it\n");
    log_out(output_file, "under certain conditions; type '-license' for details.\n");
    log_out(output_file, "\tQuestions and bug reports to: [email protected]\n");
    log_out(output_file, "\tPlease include in published work based on Roulattice:\n");
    log_out(output_file, "\t\tDietschreit, J. C. B.; Diestler, D. J.; Knapp, E. W.,\n");
    log_out(output_file, "\t\tModels for Self-Avoiding Polymer Chains on the Tetrahedral Lattice.\n");
    log_out(output_file, "\t\tMacromol. Theory Simul. 2014, 23, 452-463\n");
    log_out(output_file, "-----------------------------------------------------------------------------------\n");
    
    
    
    /* get the arguments from the comand line */
    getArgs(output_file, argc, argv);
    
    
    //------------------------------------------------------------------------------------
    // for reading DCD-files
    // this has to be early in the code, because it sets the variables ARG_numberofbeads and ARG_numberofframes!
    
    // variables concerning reading dcd
    molfile_timestep_t timestep;
    void *v;
    dcdhandle *dcd;
    int natoms;
    float sizeMB =0.0, totalMB = 0.0;
    // reading the dcd-file and setting global variables accordingly
    if (ARG_typeofrun==0) {
        natoms = 0;
        v = open_dcd_read(dcdFileName, "dcd", &natoms);
        if (!v) {
            fprintf(stderr, "ERROR: open_dcd_read failed for file %s\n", dcdFileName);
            return EXIT_FAILURE;
        }
        
        dcd = (dcdhandle *)v;
        sizeMB = ((natoms * 3.0) * dcd->nsets * 4.0) / (1024.0 * 1024.0);
        totalMB += sizeMB;
        
        log_out(output_file, "Read DCD: %d atoms, %d frames, size: %6.1fMB\n", natoms, dcd->nsets, sizeMB);
        
        timestep.coords = (float *)malloc(3*sizeof(float)*natoms);
        
        ARG_numberofbeads=dcd->natoms;
        ARG_numberofframes=dcd->nsets;
    }
    //------------------------------------------------------------------------------------
    

    // print all the options to the screen so one can check whether the right thing gets computed
    print_set_options(output_file, ARG_typeofrun, ARG_flength, ARG_fflength, ARG_blength, ARG_numberofbeads, ARG_numberofframes, ARG_randomseed, ARG_bondlength, ARG_torsion, ARG_intra_potential, ARG_intra_parameter1, ARG_intra_parameter2);
    
    
    
    //-----------------------------------------------------------------------------------------------------------------------------------------------
    //-----------------------------------------------------------------------------------------------------------------------------------------------
    // physical constants
    
    pi = acos(-1.0);
    
    //-----------------------------------------------------------------------------------------------------------------------------------------------
    //-----------------------------------------------------------------------------------------------------------------------------------------------
    
    
    /* Initialize the most important variables */
    
    // stuff with bond lengths
    const double inv_sqrt3 = 1.0/sqrt(3.0);
    const double bondlength = ARG_bondlength;
    double recast_factor;
    if (ARG_typeofrun<40){// this recasts walk on diamond lattice
        recast_factor = inv_sqrt3*bondlength;
    }
    else {// this is for runs on simple cubic lattice
        recast_factor = bondlength;
    }
    
    // variables with atom numbers etc
    const int last_atom = ARG_numberofbeads -1;
    const unsigned int number_of_torsions = ARG_numberofbeads -3;
    // number of frag, fragfags, endfrags, fragbricks, endbricks
    unsigned int numof_frags_bricks[5] = {0};
    
    
    // fractions of the number of frames
    const unsigned long permill_frames = ARG_numberofframes / 1000; // used for convergence
    const unsigned long percent_frames = ARG_numberofframes / 100; // used for ramining time
    const unsigned long tenth_frames = ARG_numberofframes / 10; // used for error estimation
    int cent;
    int tenth;
    
    int counter; // counter which can be used at any parts of the main programm, should only be used locally in a loop
    
    
    // basic moves on the tetrahedral lattice, back and forth
    const int move[2][4][3] = {
        {
            {-1, -1, -1},
            {1, 1, -1},
            {1, -1, 1},
            {-1, 1, 1}
        },
        {
            {1, 1, 1},
            {-1, -1, 1},
            {-1, 1, -1},
            {1, -1, -1}
        }
    };
    
    // moves possible in SAW (no walking back)
    const int sawmoves[4][3] = {
        {1, 2, 3},
        {0, 2, 3},
        {0, 1, 3},
        {0, 1, 2}
    };
    
    
    //-----------------------------------------------------------------------
    // building bricks are used to put parts together which are pre-checked
    int ***building_bricks=NULL;
    
    int numberofbricks;
    
    if (ARG_typeofrun==13 || ARG_typeofrun==14 || ARG_typeofrun==23 || ARG_typeofrun==24 || ARG_typeofrun==33 || ARG_typeofrun==34){
        
        // thise generates the bricks
        building_bricks = make_bricks_saw(building_bricks, move, sawmoves, ARG_blength, &numberofbricks, ARG_strictness);
        if (NULL==building_bricks[0][0]){
            return EXIT_FAILURE;
        }
        
        log_out(output_file, "%d bricks were generated, with a length of %d \n", numberofbricks, ARG_blength);
        
    }
    
    
    
    //----------------------------------------------------------------------------------------------------------------------------------------------------------
    //----------------------------------------------------------------------------------------------------------------------------------------------------------
    
    /* Initialize beads vector and set all values to zero */
    int **int_polymer;
    int_polymer = calloc(ARG_numberofbeads, sizeof(int *));
    
    double **double_polymer;
    double_polymer = calloc(ARG_numberofbeads, sizeof(double *));
    
    for (int dim1=0; dim1<ARG_numberofbeads;dim1++){
        
        int_polymer[dim1] = calloc(3, sizeof(int *));
        double_polymer[dim1] = calloc(3, sizeof(double *));
        
    }
    
    
    //----------------------------------------------------------------------------------------------------------------------------------------------------------
    //----------------------------------------------------------------------------------------------------------------------------------------------------------
    // observables
    
    OBSERVABLE normal_obs;
    
    normal_obs.maxee = 0.0; // maximal stretch of polymer
    
    OBSERVABLE intra_obs[100];

    //-------------------------------------------------------
    // initialization of all the OBSERVABLE variables
    //-------------------------------------------------------
    
    normal_obs.err_ee2 = (double *) calloc(11, sizeof(double));
    if(NULL == normal_obs.err_ee2) {
        fprintf(stderr, "Allocation of ee2 variable failed! \n");
        return EXIT_FAILURE;
    }
    normal_obs.err_rgyr = (double *) calloc(11, sizeof(double));
    if(NULL == normal_obs.err_rgyr) {
        fprintf(stderr, "Allocation of rgyr variable failed! \n");
        return EXIT_FAILURE;
    }
    
    if (ARG_intra_potential>0) {
        for (int dim1=0; dim1<100; dim1++) {
            intra_obs[dim1].err_ee2 =(double *) calloc(11, sizeof(double));
            intra_obs[dim1].err_rgyr =(double *) calloc(11, sizeof(double));
            if(NULL == intra_obs[dim1].err_ee2 || NULL == intra_obs[dim1].err_rgyr) {
                fprintf(stderr, "Allocation of ee2 or rgyr variable (intramolecular) failed! \n");
                return EXIT_FAILURE;
            }
        }
    }
    
    
    // initializes the observables for torsional analysis (optional)
    if (ARG_torsion==1) {
        normal_obs.err_pt = (double *) calloc(11, sizeof(double));
        if(NULL == normal_obs.err_pt) {
            fprintf(stderr, "Allocation of torsion variable failed! \n");
            return EXIT_FAILURE;
        }
        
        if (ARG_intra_potential>0) {
            for (int dim1=0; dim1<100; dim1++) {
                intra_obs[dim1].pt = 0.0;
                intra_obs[dim1].err_pt = (double *) calloc(11, sizeof(double));
                if(NULL == intra_obs[dim1].err_pt) {
                    fprintf(stderr, "Allocation of torsion variable (intramolecular) failed! \n");
                    return EXIT_FAILURE;
                }
            }
        }
    }
    
    // initializes the observables for loss of solven accessible surface area analysis (optional)
    if (ARG_sasa==1){
        normal_obs.err_dsasa = (double *) calloc(11, sizeof(double));
        if(NULL == normal_obs.err_dsasa) {
            fprintf(stderr, "Allocation of D-SASA variable failed! \n");
            return EXIT_FAILURE;
        }
        
        if (ARG_intra_potential>0) {
            for (int dim1=0; dim1<100; dim1++) {
                intra_obs[dim1].dsasa = 0.0;
                intra_obs[dim1].err_dsasa = (double *) calloc(11, sizeof(double));
                if(NULL == intra_obs[dim1].err_dsasa) {
                    fprintf(stderr, "Allocation of D-SASA variable (intramolecular) failed! \n");
                    return EXIT_FAILURE;
                }
            }
        }
    }
    
    // this is needed for the pair correlation function
    double *pair_correlation_obs;
    if (ARG_pair_correlation==1) {
        pair_correlation_obs = (double*) calloc(2*ARG_numberofbeads, sizeof(double));
        if(NULL == pair_correlation_obs) {
            fprintf(stderr, "Allocation of pair_correlation_obs failed! \n");
            return EXIT_FAILURE;
        }
        
        normal_obs.pair_corr = (double *) calloc(2*ARG_numberofbeads, sizeof(double));
        if(NULL == normal_obs.pair_corr) {
            fprintf(stderr, "Allocation of pair_corr failed! \n");
            return EXIT_FAILURE;
        }
        
        if (ARG_intra_potential>0) {
            for (int dim1=0; dim1<100; dim1++) {
                intra_obs[dim1].pair_corr = (double *) calloc(2*ARG_numberofbeads, sizeof(double));
                if(NULL == intra_obs[dim1].pair_corr) {
                    fprintf(stderr, "Allocation of pair_corr (intramolecular) failed! \n");
                    return EXIT_FAILURE;
                }
            }
        }
    }
    //-------------------------
    
    
    // this will provide a measure for entropy loss calculation
    unsigned long *attempts_successes;
    double *log_attempts;
    log_attempts = (double*) calloc(11, sizeof(double));
    
    // set the number of entries in this list, it depends on the typeofrun, but not the saw-type
    // last entry is the recast number of attempts which provides a measure for the entropy loss
    
    //-------------------------------------------------------------------------------------------
    //-------------------------------------------------------------------------------------------
    // calculate variables which depend on the typeofrun
    
    
    switch (ARG_typeofrun) {
            // normal SAWX
        case 10:
        case 20:
        case 30:
            attempts_successes = calloc(2, sizeof(unsigned long));
            break;
            // fSAWX
        case 11:
        case 21:
        case 31:
            attempts_successes = calloc(5, sizeof(unsigned long));
            numof_frags_bricks[0] = (ARG_numberofbeads-1)/ARG_flength;
            break;
            // bSAWX
        case 13:
        case 23:
        case 33:
            attempts_successes = calloc(3, sizeof(unsigned long));
            numof_frags_bricks[3] = (ARG_numberofbeads-1)/ARG_blength;
            break;
            // fb_SAWX
        case 14:
        case 24:
        case 34:
            attempts_successes = calloc(5, sizeof(unsigned long));
            numof_frags_bricks[0] = (ARG_numberofbeads-1)/ARG_flength;
            numof_frags_bricks[3] = ARG_flength/ARG_blength;
            numof_frags_bricks[4] = (ARG_numberofbeads-1-ARG_flength*numof_frags_bricks[3])/ARG_blength;
            break;
            
        default:
            break;
    }
    
    
    //----------------------------------------------------------------------------------------------------------------------------------------------------------
    //----------------------------------------------------------------------------------------------------------------------------------------------------------
    // intra molecular interactions
    
    
    // boltzman-factors, the intramolecular energy, the enrgy time the boltzmanfactor (entropy)
    double *intra_boltzman_factors;
    double *intra_highest_boltzmanfactor;
    double *intra_energy;
    double **intra_sum_of_boltzfactors;
    double **intra_sum_of_enrgyboltz;
    int *intra_interactions_hist;
 //   double *intra_interactions_testhist;
    
    double intra_max_factor = 0.0;
    double intra_min_factor = 0.0;
    
    // binning the energies of the intra-factors
    double intra_binmin;
    double intra_binmax;
    double intra_binwidth;
    int **intra_energybin;
    
    
    
    // these will be the parameter of the intra molecular force
    double *intra_parameter1;
    double *intra_parameter2;
    
    
    
    if (ARG_intra_potential > 0){
        switch (ARG_intra_potential) {
                // 1-10 potential well + torsional potential, given energy values
            case 1:
                intra_boltzman_factors = (double*) calloc(1, sizeof(double));
                intra_highest_boltzmanfactor = (double*) calloc(1, sizeof(double));
                intra_energy = (double*) calloc(1, sizeof(double));
                intra_sum_of_boltzfactors = (double**) calloc(1, sizeof(double));
                intra_sum_of_enrgyboltz = (double**) calloc(1, sizeof(double*));
                intra_sum_of_boltzfactors[0] = (double*) calloc(10, sizeof(double));
                intra_sum_of_enrgyboltz[0]  = (double*) calloc(10, sizeof(double));
                
                intra_parameter1 = (double*) malloc(1 * sizeof(double));
                intra_parameter2 = (double*) malloc(1 * sizeof(double));
                intra_interactions_hist = calloc(ARG_numberofbeads, sizeof(int));
 //               intra_interactions_testhist = calloc(100, sizeof(double));
                intra_parameter1[0] = ARG_intra_parameter1[0]; // nearest neighbor potential
                intra_parameter2[0] = ARG_intra_parameter2[0]; // torsion potential
                intra_binmin = -100.0;
                intra_binmax = 100.0;
                intra_binwidth = 1.0;
                intra_energybin = (int**) calloc(1, sizeof(int *));
                intra_energybin[0] = (int*) calloc(((intra_binmax-intra_binmin)/intra_binwidth), sizeof(int));
                break;
                
                // 1-10 potential well + torsional potential, given energy value range! 10x10
            case 2:
                intra_boltzman_factors = (double*) calloc(100, sizeof(double));
                intra_highest_boltzmanfactor = (double*) calloc(100, sizeof(double));
                intra_energy = (double*) calloc(100, sizeof(double));
                intra_sum_of_boltzfactors = (double**) calloc(100, sizeof(double));
                intra_sum_of_enrgyboltz = (double**) calloc(100, sizeof(double*));
                
                for (int dim1=0; dim1<100; ++dim1) {
                    intra_sum_of_boltzfactors[dim1] = (double*) calloc(10, sizeof(double));
                    intra_sum_of_enrgyboltz[dim1]  = (double*) calloc(10, sizeof(double));
                }
                
                intra_parameter1 = (double*) malloc(10 * sizeof(double));
                intra_parameter2 = (double*) malloc(10 * sizeof(double));
                intra_interactions_hist = calloc(ARG_numberofbeads, sizeof(int));
 //               intra_interactions_testhist = calloc(100, sizeof(double));
                for (int dim1=0; dim1<10; dim1++) {
                    intra_parameter1[dim1] = ARG_intra_parameter1[0]+ ARG_intra_parameter1[1]*(double)dim1; // nearest neighbor potential
                    intra_parameter2[dim1] = ARG_intra_parameter2[0]+ ARG_intra_parameter2[1]*(double)dim1; // torsion potential
                }
                intra_binmin = -100.0;
                intra_binmax = 100.0;
                intra_binwidth = 1.0;
                intra_energybin = (int**) calloc(100, sizeof(int *));
                for (int dim1=0; dim1<100; ++dim1){
                    intra_energybin[dim1] = (int*) calloc(((intra_binmax-intra_binmin)/intra_binwidth), sizeof(int));
                }
                break;
                
            default:
                fprintf(stderr, "This intramolecular potential doesn't exist! \n");
                break;
        }

    }

    
    
//----------------------------------------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------------------------------------------------

    
    
    
    
    /* start of chain generation*/
    time[1] = time_of_day();
    
    for (unsigned long frame=0; frame<ARG_numberofframes; frame++){
        
        tenth = frame/tenth_frames;
        
        switch(ARG_typeofrun){
                
            case 0:
                dcd_to_polymer(double_polymer, v, natoms, &timestep, dcd, frame, ARG_numberofbeads);
                break;
                
            case 1:
                tetra_rw(int_polymer, move, ARG_numberofbeads);
                break;
                
            case 2:
                tetra_fww(int_polymer, move, sawmoves, ARG_numberofbeads);
                break;
                
            case 10:
                tetra_saw1(int_polymer, move, sawmoves, ARG_numberofbeads, attempts_successes);
                break;
                
            case 11:
                tetra_fsaw1(int_polymer, move, sawmoves, ARG_numberofbeads, ARG_flength, attempts_successes);
                break;
                
            case 13:
                tetra_bsaw1(int_polymer, move, sawmoves, ARG_numberofbeads, ARG_blength, numberofbricks, building_bricks, attempts_successes);
                break;
                
   //         case 14: // here is something awfully wrong, can't find the mistake at the moment!
   //             tetra_fb_saw1(int_polymer, move, sawmoves, ARG_numberofbeads, ARG_blength, numberofbricks, building_bricks, ARG_flength, attempts_successes);
   //             break;
                
            case 20:
                tetra_saw2(int_polymer, move, sawmoves, ARG_numberofbeads, attempts_successes);
                break;
                
            case 21:
                tetra_fsaw2(int_polymer, move, sawmoves, ARG_numberofbeads, ARG_flength, attempts_successes);
                break;
                
            case 23:
                tetra_bsaw2(int_polymer, move, sawmoves, ARG_numberofbeads, ARG_blength, numberofbricks, building_bricks, attempts_successes);
                break;
                
            case 24:
                tetra_fb_saw2(int_polymer, move, sawmoves, ARG_numberofbeads, ARG_blength, numberofbricks, building_bricks, ARG_flength, attempts_successes);
                break;
                
            case 30:
                tetra_saw3(int_polymer, move, sawmoves, ARG_numberofbeads, attempts_successes);
                break;

            case 31:
                tetra_fsaw3(int_polymer, move, sawmoves, ARG_numberofbeads, ARG_flength, attempts_successes);
                break;
                
            case 33:
                tetra_bsaw3(int_polymer, move, sawmoves, ARG_numberofbeads, ARG_blength, numberofbricks, building_bricks, attempts_successes);
                break;
                
            case 34:
                tetra_fb_saw3(int_polymer, move, sawmoves, ARG_numberofbeads, ARG_blength, numberofbricks, building_bricks, ARG_flength, attempts_successes);
                break;

                
            default:
                log_out(output_file, "ERROR: ARG_typeofrun = %d isn't recognized by the main part of the programm!\n", ARG_typeofrun);
                usage_error();
                
        } // end of chain generaiton
        
        
        // copies the lattice polymer into an array with doubles so that the chosen bond length can be used.
        if (ARG_typeofrun>0) {
            recast(double_polymer, int_polymer, ARG_numberofbeads, &recast_factor);
        }
        
        
        //-----------------------------------------------------------------------------
        //-----------------------------------------------------------------------------
        // get most important observables
        
        // end-to-end distance^2
        normal_obs.ee2 = double_distance2(double_polymer[last_atom], double_polymer[0]);
        normal_obs.err_ee2[tenth] += normal_obs.ee2;
        // radius of gyration
        normal_obs.rgyr = radius_of_gyration(double_polymer, ARG_numberofbeads);
        normal_obs.err_rgyr[tenth] += normal_obs.rgyr;
        // pT
        if (ARG_torsion==1){
            normal_obs.pt = get_nT(double_polymer, number_of_torsions);
            normal_obs.err_pt[tenth] += normal_obs.pt;
        }
        if (ARG_sasa==1){
            //observables[4] = get_asa(double_polymer, ARG_numberofbeads, (sqrt(16.0/3.0)*bondlength/2.0));
            normal_obs.dsasa = delta_asa(double_polymer, ARG_numberofbeads, bondlength);
            normal_obs.err_dsasa[tenth] += normal_obs.dsasa;
        }
        if (ARG_pair_correlation==1) {
            if (false==pair_correlation_fct(pair_correlation_obs, double_polymer, ARG_numberofbeads)){
                return EXIT_FAILURE;
            }
            for (int pairs=0; pairs<(2*ARG_numberofbeads); pairs++) {
                normal_obs.pair_corr[pairs] += pair_correlation_obs[pairs];
            }
        }
        
        
        

        
        
        
        
        
        //-----------------------------------------------------------------------------
        //-----------------------------------------------------------------------------
        // calculate boltzman factors if intramolecular forces are switched on
        
        switch (ARG_intra_potential) {
                
            // torsion + square well potential
            case 1:
                intrapot_torsion_well(intra_boltzman_factors, intra_energy, intra_interactions_hist, intra_highest_boltzmanfactor, intra_parameter1, intra_parameter2, normal_obs.pt, number_of_torsions, int_polymer, ARG_numberofbeads);
                
                intra_sum_of_enrgyboltz[0][tenth] += (intra_boltzman_factors[0]*intra_energy[0]);
                intra_sum_of_boltzfactors[0][tenth] += intra_boltzman_factors[0];
                
                intra_obs[0].err_ee2[tenth] += normal_obs.ee2 * intra_boltzman_factors[0];
                intra_obs[0].err_rgyr[tenth] += normal_obs.rgyr * intra_boltzman_factors[0];
                intra_obs[0].err_pt[tenth] += normal_obs.pt * intra_boltzman_factors[0];
                
                intra_binenergy(intra_energy[0], intra_binmin, intra_binwidth, intra_energybin[0]);
                
                // pair correlation function
                if (ARG_pair_correlation==1){
                    for (int pairs=0; pairs<(2*ARG_numberofbeads); pairs++) {
                        intra_obs[0].pair_corr[pairs] += (pair_correlation_obs[pairs]*intra_boltzman_factors[0]);
                    }
                }
                break;
                
            // torsion + square well potential, range of energy values
            case 2:
                intrapot_torsion_well_scan(intra_boltzman_factors, intra_energy, intra_interactions_hist, intra_highest_boltzmanfactor, intra_parameter1, intra_parameter2, normal_obs.pt, number_of_torsions, int_polymer, ARG_numberofbeads);
                //intrapot_torsion_well_test(intra_boltzman_factors, intra_energy, intra_interactions_hist, intra_interactions_testhist,intra_highest_boltzmanfactor, intra_parameter1, intra_parameter2, normal_obs.pt, number_of_torsions, int_polymer, ARG_numberofbeads);
                
                for (int dim1=0; dim1<100; ++dim1) {
                    intra_sum_of_enrgyboltz[dim1][tenth] += (intra_boltzman_factors[dim1]*intra_energy[dim1]);
                    intra_sum_of_boltzfactors[dim1][tenth] += intra_boltzman_factors[dim1];
                    intra_obs[dim1].err_ee2[tenth] += normal_obs.ee2 * intra_boltzman_factors[dim1];
                    intra_obs[dim1].err_rgyr[tenth] += normal_obs.rgyr * intra_boltzman_factors[dim1];
                    intra_obs[dim1].err_pt[tenth] += normal_obs.pt * intra_boltzman_factors[dim1];
                    intra_binenergy(intra_energy[dim1], intra_binmin, intra_binwidth, intra_energybin[dim1]);
                    // pair correlation function
                    if (ARG_pair_correlation==1){
                        for (int pairs=0; pairs<(2*ARG_numberofbeads); pairs++) {
                            intra_obs[dim1].pair_corr[pairs] += (pair_correlation_obs[pairs]*intra_boltzman_factors[dim1]);
                        }
                    }
                }
                
                break;
                
            default:
                break;
                
        }// boltzman factors and energies have been determined
            // end of anything related to intramolecular potentials
        
        
        
        //--------------------------------------------------------------------------------------------
        //--------------------------------------------------------------------------------------------
        // everything has been calculated, now is the opportunity to look at convergence
        
        if ((frame+1)%permill_frames==0) {
            // convergence of variables with equal weights
            convergence(&normal_obs, (double)number_of_torsions, (frame+1), conv_obs_file);
            
            
            switch (ARG_intra_potential) {
                    
                case 1:
                    weighted_convergence(intra_obs, 1,intra_sum_of_boltzfactors, (double)number_of_torsions, (frame+1), conv_intraobs_file);
                    weights_growth(intra_sum_of_boltzfactors, 1, (frame+1), convergence_intraweights);
                    break;
                    
                    // convergence of weighted ensemble
                case 2:
                    weighted_convergence(intra_obs, 100, intra_sum_of_boltzfactors, (double)number_of_torsions, (frame+1), conv_intraobs_file);
                    weights_growth(intra_sum_of_boltzfactors, 100, (frame+1), convergence_intraweights);
                    break;
                    
                default:
                    break;
            }
            
            
            if ((frame+1)%percent_frames==0) {
                
                cent = (frame+1)/percent_frames;
                
                log_out(output_file, "Finished %i%%\t...remaining time: %f seconds \n", (cent), ((time_of_day()-time[1])*(100-cent)/(cent)));
                
                if ((frame+1)%tenth_frames==0) {
                    // every bin after the first will also include the attempts in the previous bin!
                    log_attempts[tenth] = recalc_attempts(attempts_successes, numof_frags_bricks, numberofbricks, ARG_typeofrun);
                }
                
                
            }
        }
        
    } // end of loop over number of frames
    
    
    

    
    
    //----------------------------------------------------------------------------------------------------------------------------------------------------------
    //----------------------------------------------------------------------------------------------------------------------------------------------------------
    
    /* Post-Process */
    time[2] = time_of_day();
    
    // Maybe there should be a function, which returns means and errors; it calls these subroutines ....
    
    log_attempts[10] = recalc_attempts(attempts_successes, numof_frags_bricks, numberofbricks, ARG_typeofrun);
    for (int dim1=9; dim1>0; --dim1) {
        log_attempts[dim1] = log( exp(log_attempts[dim1]) - exp(log_attempts[dim1-1]) );
    }
    
    // get means and errors
    normal_obs.ee2 = sqrt( average(normal_obs.err_ee2, ARG_numberofframes) );
    normal_obs.err_ee2[10] = error_sq_ten(normal_obs.ee2, normal_obs.err_ee2, ARG_numberofframes);
    normal_obs.rgyr = sqrt( average(normal_obs.err_rgyr, ARG_numberofframes) );
    normal_obs.err_rgyr[10] = error_sq_ten(normal_obs.rgyr, normal_obs.err_rgyr, ARG_numberofframes);
    normal_obs.S = (log((double)ARG_numberofframes) - log_attempts[10]);
    
    if (ARG_torsion==1) {
        normal_obs.pt = average(normal_obs.err_pt, ARG_numberofframes);
        normal_obs.err_pt[10] = error_ten(normal_obs.pt, normal_obs.err_pt, ARG_numberofframes);
    }
    if (ARG_sasa==1) {
        normal_obs.dsasa = average(normal_obs.err_dsasa, ARG_numberofframes);
        normal_obs.err_dsasa[10] = error_ten(normal_obs.dsasa, normal_obs.err_dsasa, ARG_numberofframes);
    }
    
    
    
    //----------------------------------------------------------------------------------------------------------------------------------------------------------
    //----------------------------------------------------------------------------------------------------------------------------------------------------------
    
    /* Output */
    time[3] = time_of_day();
    
    // print the output to screen and to the output_file
    
    log_out(output_file, "\n-----------------------------------------------------------------------------------\n");
    log_out(output_file, "FINAL OUTPUT\n");
    
    log_out(output_file, "\nEntropic Considerations:\n");
    log_out(output_file, "Attempts to Compute the Ensemble: %e  \n", exp(log_attempts[10]));
    log_out(output_file, "\tDelta S / k_B (FWW -> SAWn): %f \n",  normal_obs.S);
    
    log_out(output_file, "\nChosen Observables:\n");
    log_out(output_file, "Flory Radius: %f +- %f \n", normal_obs.ee2, normal_obs.err_ee2[10]);
    log_out(output_file, "Radius of Gyration: %f +- %f \n", normal_obs.rgyr, normal_obs.err_rgyr[10]);
    if (ARG_torsion==1) {
        log_out(output_file, "Probability of trans = %f +- %f\n", (normal_obs.pt/(double)number_of_torsions), (normal_obs.err_pt[10]/(double)number_of_torsions));

    }
    if (ARG_sasa==1) {
        log_out(output_file, "Delta SASA = %f +- %f\n", normal_obs.dsasa, normal_obs.err_dsasa[10]);
    }
    if (ARG_pair_correlation==1) {
        log_out(output_file, "The pair-correlation function was written to 'pair_correlation_function.dat'.\n");
    }

    log_out(output_file, "\nThis ouput is also written to 'output_file.dat'.\n");
    log_out(output_file, "The convergence was written to 'convergence_obs.dat'.\n");
    
    
    if (ARG_intra_potential>0) {
        log_out(output_file, "\nThe Boltzmann-weighted observables can be found in 'intramolecular_obs.dat'.\n");
        log_out(output_file, "The Boltzmann-weighted convergence was written to 'intramolecular_convergence_obs.dat'.\n");
        log_out(output_file, "A histogram of the Boltzmann-factors was written to 'intramolecular_factors_hist.dat'.\n");
        log_out(output_file, "The sum of the Boltzmann-factors was written to 'intramolecular_convergence_Z.dat'.\n");
        log_out(output_file, "A histogram of the intramolecular contacts was written to 'intramolecular_interactions_hist.dat'.\n");
    }
    
    

    //----------------------------------------------------------------------------------------------------------------------------------------------------------
    //----------------------------------------------------------------------------------------------------------------------------------------------------------
    
    /* Output to file */
    
    // pair correlation function
    if (ARG_pair_correlation==1){
        
        if (ARG_intra_potential==0) {
            fprintf(pair_correl_file,"# r_0-r_1 pair_correlation \n");
            for (int dim1=0; dim1<(2*ARG_numberofbeads); dim1++){
                fprintf(pair_correl_file, "%i %e \n", dim1, (normal_obs.pair_corr[dim1]/(double)ARG_numberofframes));
            }
        }
        else if (ARG_intra_potential==2){
            fprintf(pair_correl_file,"# r_0-r_1 pair_correlation(unweigthed) pair_correlation(weigthed)\n");
            for (int dim1=0; dim1<(2*ARG_numberofbeads); dim1++){
                fprintf(pair_correl_file, "%i %e %e \n", dim1, (normal_obs.pair_corr[dim1]/(double)ARG_numberofframes), (intra_obs[46].pair_corr[dim1]/average(intra_sum_of_boltzfactors[46], 1)));
            }
        }
        
        
    }
    
    
    
    switch (ARG_intra_potential) {
            
        case 1:
            // prints the weighted observables to file with error estimate
            fprintf(intra_pot_file, "### 1-9 well, torsion eps, Rf, Rf_err, Rg, Rg_err, pT, pT_err, DS, DS_err, <exp(-E/kT)>/exp(-Emax/kT) \n" );

            intra_obs[0].ee2 = sqrt(weighted_average(intra_obs[0].err_ee2, intra_sum_of_boltzfactors[0]));
            intra_obs[0].err_ee2[10] = weighted_error_sq_ten(intra_obs[0].ee2, intra_obs[0].err_ee2, intra_sum_of_boltzfactors[0]);
            
            intra_obs[0].rgyr = sqrt(weighted_average(intra_obs[0].err_rgyr, intra_sum_of_boltzfactors[0]));
            intra_obs[0].err_rgyr[10] = weighted_error_sq_ten(intra_obs[0].rgyr, intra_obs[0].err_rgyr, intra_sum_of_boltzfactors[0]);
            
            intra_obs[0].pt = weighted_average(intra_obs[0].err_pt, intra_sum_of_boltzfactors[0]);
            intra_obs[0].err_pt[10] = weighted_error_ten(intra_obs[0].pt, intra_obs[0].err_pt, intra_sum_of_boltzfactors[0]);
            
            intra_obs[0].S = intra_entropy(intra_sum_of_boltzfactors[0], intra_sum_of_enrgyboltz[0], log_attempts[10]);
            intra_obs[0].err_S = intra_entropy_error_ten(intra_obs[0].S, intra_sum_of_boltzfactors[0], intra_sum_of_enrgyboltz[0], log_attempts);
            
            fprintf(intra_pot_file, "%f %f %e %e %e %e %e %e %e %e %e \n", intra_parameter1[0], intra_parameter2[0], intra_obs[0].ee2, intra_obs[0].err_ee2[10], intra_obs[0].rgyr, intra_obs[0].err_rgyr[10], (intra_obs[0].pt/(double)number_of_torsions), (intra_obs[0].err_pt[10]/(double)number_of_torsions), intra_obs[0].S, intra_obs[0].err_S, intra_loss_of_conf(intra_sum_of_boltzfactors[0], intra_highest_boltzmanfactor[0], ARG_numberofframes));

            
            // histogram over 1-9 interacitons
            fprintf(intra_interactions_file, "# number-of-nn-interactions, occurence \n");
            for (int dim1=0; dim1<ARG_numberofbeads; ++dim1) {
                fprintf(intra_interactions_file, "%i %i \n", dim1, intra_interactions_hist[dim1]);
            }
            
            // test histogram
            //      fprintf(intra_interactions_testfile, "# sperating-bonds 0_contacts 1_contacts 2_contacts\n");
            //      for (int dim1=0; dim1<98; dim1+=3) {
            //          fprintf(intra_interactions_testfile, "%i %e %e %e \n", (dim1/3+4), intra_interactions_testhist[dim1]/average(intra_sum_of_boltzfactors[46], 1), intra_interactions_testhist[dim1+1]/average(intra_sum_of_boltzfactors[46], 1), intra_interactions_testhist[dim1+2]/average(intra_sum_of_boltzfactors[46], 1));
            //     }
            
            // histogram of intra energies
            fprintf(intra_boltzman_factors_hist, "# energy, bincount-for-these-parameters");
            for (int dim1=0; dim1<((intra_binmax-intra_binmin)/intra_binwidth); ++dim1) {
                fprintf(intra_boltzman_factors_hist, "%f %i \n", (intra_binmin+(double)dim1*intra_binwidth), intra_energybin[0][dim1]);
            }
            break;
            
        case 2:
            // prints the weighted observables to file with error estimate
            fprintf(intra_pot_file, "### 1-9 well, torsion eps, Rf, Rf_err, Rg, Rg_err, pT, pT_err, DS, DS_err, <exp(-E/kT)>/exp(-Emax/kT) \n" );
            for (int dim1=0; dim1<10; dim1++) {
                for (int dim2=0; dim2<10; dim2++) {
                    
                    counter = dim1*10 + dim2;
                    
                    intra_obs[counter].ee2 = sqrt(weighted_average(intra_obs[counter].err_ee2, intra_sum_of_boltzfactors[counter]));
                    intra_obs[counter].err_ee2[10] = weighted_error_sq_ten(intra_obs[counter].ee2, intra_obs[counter].err_ee2, intra_sum_of_boltzfactors[counter]);
                    
                    intra_obs[counter].rgyr = sqrt(weighted_average(intra_obs[counter].err_rgyr, intra_sum_of_boltzfactors[counter]));
                    intra_obs[counter].err_rgyr[10] = weighted_error_sq_ten(intra_obs[counter].rgyr, intra_obs[counter].err_rgyr, intra_sum_of_boltzfactors[counter]);
                    
                    intra_obs[counter].pt = weighted_average(intra_obs[counter].err_pt, intra_sum_of_boltzfactors[counter]);
                    intra_obs[counter].err_pt[10] = weighted_error_ten(intra_obs[counter].pt, intra_obs[counter].err_pt, intra_sum_of_boltzfactors[counter]);
                    
                    intra_obs[counter].S = intra_entropy(intra_sum_of_boltzfactors[counter], intra_sum_of_enrgyboltz[counter], log_attempts[10]);
                    intra_obs[counter].err_S = intra_entropy_error_ten(intra_obs[counter].S, intra_sum_of_boltzfactors[counter], intra_sum_of_enrgyboltz[counter], log_attempts);
                    
                    fprintf(intra_pot_file, "%f %f %e %e %e %e %e %e %e %e %e \n", intra_parameter1[dim1], intra_parameter2[dim2], intra_obs[counter].ee2, intra_obs[counter].err_ee2[10], intra_obs[counter].rgyr, intra_obs[counter].err_rgyr[10], (intra_obs[counter].pt/(double)number_of_torsions), (intra_obs[counter].err_pt[10]/(double)number_of_torsions), intra_obs[counter].S, intra_obs[counter].err_S, intra_loss_of_conf(intra_sum_of_boltzfactors[counter], intra_highest_boltzmanfactor[counter], ARG_numberofframes));
                }
            }
            
            // histogram over 1-9 interacitons
            fprintf(intra_interactions_file, "# number-of-nn-interactions, occurence \n");
            for (int dim1=0; dim1<ARG_numberofbeads; ++dim1) {
                fprintf(intra_interactions_file, "%i %i \n", dim1, intra_interactions_hist[dim1]);
            }
            
            // test histogram
            //      fprintf(intra_interactions_testfile, "# sperating-bonds 0_contacts 1_contacts 2_contacts\n");
            //      for (int dim1=0; dim1<98; dim1+=3) {
            //          fprintf(intra_interactions_testfile, "%i %e %e %e \n", (dim1/3+4), intra_interactions_testhist[dim1]/average(intra_sum_of_boltzfactors[46], 1), intra_interactions_testhist[dim1+1]/average(intra_sum_of_boltzfactors[46], 1), intra_interactions_testhist[dim1+2]/average(intra_sum_of_boltzfactors[46], 1));
            //     }
            
            // histogram of intra energies
            fprintf(intra_boltzman_factors_hist, "# energy, bincount-for-these-parameters");
            for (int dim1=0; dim1<((intra_binmax-intra_binmin)/intra_binwidth); ++dim1) {
                fprintf(intra_boltzman_factors_hist, "%f ", (intra_binmin+(double)dim1*intra_binwidth));
                for (int dim2=0; dim2<100; ++dim2) {
                    fprintf(intra_boltzman_factors_hist, "%i ", intra_energybin[dim2][dim1]);
                }
                fprintf(intra_boltzman_factors_hist, "\n");
            }

            break;
            
        default:
            break;
    }


    
    
    
    
    log_out(output_file, "\nComputation of Chains:\t%f seconds \nTotal Runtime:\t\t%f seconds \n\n", (time[2]-time[1]), (time[3]-time[0]));
    log_out(output_file, "End of Programm!\n-----------------------------------------------------------------------------------\n");
    
    // make sure everything gets printed
    fflush(stdout);
    
    
    
    //----------------------------------------------------------------------------------------------------------------------------------------------------------
    //----------------------------------------------------------------------------------------------------------------------------------------------------------
    // close every remaining file and free remaining pointers!
    // cleaning up ;-)
    
    //close all files
    if (ARG_typeofrun==0){// dcd-file
        close_file_read(v);
    }
    
    fclose(conv_obs_file);
    fclose(pair_correl_file);
    fclose(intra_pot_file);
    fclose(intra_boltzman_factors_hist);
    fclose(convergence_intraweights);
    fclose(intra_interactions_file);
    fclose(conv_intraobs_file);
    
    // very last file to close
    fclose(output_file);
    
    
    
    //-----------------------------
    // free pointers
    
    
    // free general variables
    free(normal_obs.err_ee2);
    free(normal_obs.err_rgyr);
    
    // torsion angles
    if (ARG_torsion==1) {
        free(normal_obs.err_pt);
        if (ARG_intra_potential>0) {
            for (int dim1=0; dim1<100; dim1++) {
                free(intra_obs[dim1].err_pt);
            }
        }
    }
    
    // D-SASA
    if (ARG_sasa==1) {
        free(normal_obs.err_dsasa);
        if (ARG_intra_potential>0) {
            for (int dim1=0; dim1<100; dim1++) {
                free(intra_obs[dim1].err_dsasa);
            }
        }
    }
    
    // pair correlation function
    if (ARG_pair_correlation==1) {
        free(pair_correlation_obs);
        free(normal_obs.pair_corr);
        if (ARG_intra_potential>0) {
            for (int dim1=0; dim1<100; dim1++) {
                free(intra_obs[dim1].pair_corr);
            }
        }
    }
    
    free(attempts_successes);
    
    // free arrays which held polymer coordinates
    for (int dim1=0; dim1<ARG_numberofbeads;dim1++){
        free(int_polymer[dim1]);
        free(double_polymer[dim1]);
    }
    free(int_polymer);
    free(double_polymer);
    
    
    
    // free building blocks
    if (ARG_typeofrun==13 || ARG_typeofrun==14 || ARG_typeofrun==23 || ARG_typeofrun==24 || ARG_typeofrun==33 || ARG_typeofrun==34){
        for (int dim1=0; dim1<numberofbricks; ++dim1) {
            for (int dim2=0; dim2<ARG_blength; ++dim2) {
                free(building_bricks[dim1][dim2]);
            }
            free(building_bricks[dim1]);
        }
        free(building_bricks);
    }
    
    
    
    // free potential variables
    if (ARG_intra_potential > 0){
        switch (ARG_intra_potential) {
            case 1:
                free(intra_sum_of_boltzfactors[0]);
                break;
                
            case 2:
                for (int dim1=0; dim1<100; dim1++){
                    free(intra_sum_of_boltzfactors[dim1]);
                }
                break;

            default:
                break;
        }

        free(intra_energy);
        free(intra_boltzman_factors);
        free(intra_sum_of_boltzfactors);
        free(intra_sum_of_enrgyboltz);
        free(intra_interactions_hist);
  //      free(intra_interactions_testhist);
        free(intra_parameter1);
        free(intra_parameter2);
    }
    
    
    



    
    // end of programm
    return EXIT_SUCCESS;
}
コード例 #21
0
ファイル: httppost.cpp プロジェクト: shengang1006/xxc2hd
int get_http_request(char * url, char * result, int result_len){
	
	int64 post_begin = get_tick_count();
	
	ghttp_request * request = ghttp_request_new();
	if(!request){
		log_out(log_error, "http_get::ghttp_request_new fail\n");
		return -1;
	}

	if(ghttp_set_uri(request, (char*)url) == -1){
		log_out(log_error, "http_get::ghttp_set_uri fail(%s)\n", ghttp_get_error(request));
		ghttp_request_destroy(request);
		return -1;
	}

	if(ghttp_set_type(request, ghttp_type_get) == -1) {
		log_out(log_error, "http_get::ghttp_set_type fail(%s)\n", ghttp_get_error(request));
		ghttp_request_destroy(request);
		return -1;
	}
	
	//����ͷ
	ghttp_set_header(request, http_hdr_Accept_Charset, "x-www-form-urlencoded");
	ghttp_set_header(request, http_hdr_Connection, "close");
	ghttp_set_header(request, http_hdr_Content_Type, "json");
	ghttp_set_header(request, http_hdr_Timeout, "5000");  


	if(ghttp_prepare(request) < 0){
		log_out(log_error, "http_get::ghttp_prepare fail(%s)\n", ghttp_get_error(request));
		ghttp_request_destroy(request);
		return -1;
	}
	
	ghttp_status req_status = ghttp_process(request);
	if (req_status == ghttp_error) {
		log_out(log_error, "http_get::ghttp_process url(%s) fail(%s)\n",
			url, ghttp_get_error(request));
		ghttp_request_destroy(request);
		return -1;
	}
	
	int stat_code = ghttp_status_code(request);
	if(stat_code != 200){
		log_out(log_error, "http_get::status code(%d)\n", stat_code);
		ghttp_request_destroy(request);
		return -1;
	}
	
	int	rsplen = ghttp_get_body_len(request);
	char * rspbody = ghttp_get_body(request);
	if((!rspbody) || (rsplen <= 0)){
		log_out(log_error, "http_get::ghttp_get_body fail(%s)\n", ghttp_get_error(request));
		ghttp_request_destroy(request);
		return -1;
	}
	
	if(rspbody[rsplen -1] == '\n')rsplen--;
	int ncopy = result_len < rsplen ? result_len : rsplen;
	strncpy(result, rspbody, ncopy);
	ghttp_request_destroy(request);
	
	uint take = (uint)(get_tick_count() - post_begin);
	log_out(log_debug, "http_get::take(%ums) response(%s)\n", take, result);
	
	return 0;
}
コード例 #22
0
ファイル: downloadinfo.cpp プロジェクト: shengang1006/xxc2hd
int download_info::send_data() {

    int total = 0;
    while(!m_client->get_wait_to_send_data_len()) {
        //second cache
        if(m_rfile || m_lst_filename.size()) {
            if(!m_rfile) {
                m_rfileName = m_lst_filename.front();
                m_lst_filename.pop_front();
                m_rfile = fopen(m_rfileName.c_str(), "rb");
                if(!m_rfile) {
                    log_out(log_error, "send_data::fopen fail(%s) errno(%d)\n", m_rfileName.c_str(), errno);
                    return -1;
                }
            }

            char buffer[tcp_packet_len] = {0};
            int ret = fread(buffer, 1, sizeof(buffer), m_rfile);
            if(ret <= 0) {
                log_out(log_error, "send_data::fread fail errno(%d)\n", errno);
                return -1;
            }

            if(feof(m_rfile)) {
                fclose(m_rfile);
                m_rfile = NULL;
                int ret = remove(m_rfileName.c_str());
                log_out(log_debug,"send_data::send file(%s) eof, remove(%d) errno(%d)\n",
                        m_rfileName.c_str(), ret, ret < 0 ? errno: 0);
            }

            if(send_packet(buffer, ret) < 0) {
                return -1;
            }

            m_total_send += ret;

            log_out(log_debug,"send from file(%u) total(%d)\n", ret, m_total_send);
            continue;
        }

        //third cache
        if(m_write_buffer.has) {
            int ready_sent = m_write_buffer.has > tcp_packet_len ? tcp_packet_len :m_write_buffer.has;
            m_write_buffer.has -= ready_sent;
            int ret = send_packet(m_write_buffer.buf + total, ready_sent);
            if(ret < 0) {
                return -1;
            }
            total += ready_sent;
            m_total_send += ready_sent;
            log_out(log_debug, "send from buffer(%u) total(%d)\n", ready_sent, m_total_send);
            continue;
        }

        break;
    }

    if(m_write_buffer.has && total) {
        memcpy(m_write_buffer.buf, m_write_buffer.buf + total, m_write_buffer.has);
    }

    return 0;
}
コード例 #23
0
int main(void)
{
	int listenfd = 0,connfd = 0, n=0;
	struct sockaddr_in serv_addr;
	struct sockaddr_in peer;
	logged_in = 0;
	char check[1024];
	char sendbuff[1024];
	char buffer[1024];
	char str1[1024], str2[1024];
	int numrv,size, result;
	int max_size = 1024; 
	int closed = 0; 
	int peer_len = sizeof(peer);
	pid_t pid;
	strcpy(str2,"Welcome to Online File Sharing service.\nPlease follow the instruction\n\n");
	listenfd = socket(AF_INET, SOCK_STREAM, 0);
	printf("SERVER successfully launched\n\n");

	memset(&serv_addr, '0', sizeof(serv_addr));
	memset(buffer, '0', sizeof(buffer));    
	serv_addr.sin_family = AF_INET;    
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); 
	serv_addr.sin_port = htons(5000);    

	bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr));

	if(listen(listenfd, 10) == -1){
		printf("Failed to listen\n");
		return -1;
	}


	while(1)
	{
		if(closed == 1)
			break;

		connfd = accept(listenfd, (struct sockaddr*)NULL ,NULL); // accept awaiting request
		if ( (pid = fork()) == 0 ) {
			close(listenfd);

			sendbuff[0] = '\0'; 
			strcpy(sendbuff,"Connected with server\n");
			size = max_size;	
			sendbuff[22] = '\0';

			if((n=send_mssg(connfd,sendbuff,size))==-1)
			{
				close(connfd);
				break;	
			} 
			if((n=recv_mssg(connfd, buffer, size))==-1)
				exit(1);

			else if(n==0)
				break;			

			query_check(buffer, ip, 1);
			query_check(buffer, port, 2);
			printf("%s: %s", ip, port);					

			while(1){

				if(logged_in == 0) 
				{
					strcpy(str1,"1. New Client: Register (Syntax: \"register <username> <password>\")\n2. Existing Client: Login (Syntax: \"login <username> <password>\")\n3. For closing connection(Syntax: \"close\")\n\n");
					sendbuff[0] = '\0'; 
					strcat(sendbuff,str2);
					strcat(sendbuff,str1);
					size = max_size;	
					sendbuff[strlen(str1)+strlen(str2)-1] = '\0';

					if((n=send_mssg(connfd,sendbuff,size))==-1)
					{
						close(connfd);
						break;	
					} 

					if((n=recv_mssg(connfd, buffer, size))==-1)
						exit(1);

					else if(n==0)
						break;


					if(query_check(buffer, check, 1)<0)
						strcpy(str2,"No such query\n\n");		

					else
					{
						if(strcmp(check,"register")==0)
						{
							result = register_user(buffer);
							if(result == 1)
							{
								strcpy(str2, "Successfully Registered\n\n");
							}

							else
							{
								strcpy(str2, "Unable to Register. Please try again\n\n");

							}

						}

						else if(strcmp(check,"login")==0)
						{
							result = login_user(buffer,connfd);
							if(result == 1)
							{
								strcpy(str2, "Successfully Logged in\n\n");

							}


							else
							{
								strcpy(str2, "Unable to Login. Please try again or register\n\n");

							}
						}	


						else if(strcmp(check,"close")==0)
						{
							close(connfd);
							closed = 1;
							break;	
						}


						else
							strcpy(str2, "No such query\n\n");
					}

				}

				else
				{
					strcpy(str1,"1. Share File (Syntax: \"share <filename> <filepath>\")\n2. Search a file(Syntax: \"search <filename>\")\n3. Logout from server (Syntax: \"logout\")\n\n");
					sendbuff[0] = '\0'; 
					strcat(sendbuff,str2);
					strcat(sendbuff,str1);
					size = max_size;	
					sendbuff[strlen(str1)+strlen(str2)-1] = '\0';
					if((n=send_mssg(connfd,sendbuff,size))==-1)
					{
						close(connfd);
						break;	
					} 

					if((n=recv_mssg(connfd, buffer, size))==-1)
						exit(1);

					else if(n==0)
						break;	

					if(query_check(buffer, check, 1)<0)
						strcpy(str2,"No such query\n\n");		

					else
					{
						if(strcmp(check,"share")==0)
						{
							result = share_file(buffer);
							if(result == 1)
							{
								strcpy(str2, "File successfully shared\n\n");
							}

							else
							{
								strcpy(str2, "Unable to share the file. Please try again\n\n");

							}
						}

						else if(strcmp(check,"search")==0)
						{
							char final_list[1024];
							final_list[0] = '\0';
							result = search_file(buffer, final_list);
							if(result == 1)
							{
								str2[0]='\0';	
								strcat(str2, "Search complete: RESULT: \n\n");
								if(final_list[0]=='\0')
									strcat(str2, "No match Found\n\n");
								else
									strcat(str2, final_list);

							}

							else
							{
								strcpy(str2, "Search failed\n\n");

							}
						}	

						else if(strcmp(check,"logout")==0)
						{
							log_out();	
							logged_in = 0;
							str2[0]='\0';
						}

						else
							strcpy(str2, "No such query\n");
					}


				}

			}
			log_out();
			close(connfd);
			exit(0);
		}         
		close(connfd);

	}


	return 0;
}
コード例 #24
0
/*********************************************************************************
 * The contents of this file are subject to the Common Public Attribution
 * License Version 1.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.openemm.org/cpal1.html. The License is based on the Mozilla
 * Public License Version 1.1 but Sections 14 and 15 have been added to cover
 * use of software over a computer network and provide for limited attribution
 * for the Original Developer. In addition, Exhibit A has been modified to be
 * consistent with Exhibit B.
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 * 
 * The Original Code is OpenEMM.
 * The Original Developer is the Initial Developer.
 * The Initial Developer of the Original Code is AGNITAS AG. All portions of
 * the code written by AGNITAS AG are Copyright (c) 2007 AGNITAS AG. All Rights
 * Reserved.
 * 
 * Contributor(s): AGNITAS AG. 
 ********************************************************************************/
# include	<stdlib.h>
# include	<unistd.h>
# include	<fcntl.h>
# include	<string.h>
# include	<errno.h>
# include	<sys/types.h>
# include	<sys/stat.h>
# include	"agn.h"

daemon_t *
daemon_alloc (const char *prog, bool_t background, bool_t detach) /*{{{*/
{
	daemon_t	*d;
	
	if (d = (daemon_t *) malloc (sizeof (daemon_t))) {
		d -> background = background;
		d -> detach = detach;
		d -> pid = getpid ();
		d -> pidfile = NULL;
		d -> pfvalid = false;
		if (prog) {
			const char	*ptr;
			
			if (ptr = strrchr (prog, '/'))
				++ptr;
			else
				ptr = prog;
			if (d -> pidfile = malloc (sizeof (_PATH_VARRUN) + strlen (ptr)))
				sprintf (d -> pidfile, _PATH_VARRUN "%s", ptr);
			else
				d = daemon_free (d);
		}
	}
	return d;
}/*}}}*/
daemon_t *
daemon_free (daemon_t *d) /*{{{*/
{
	if (d) {
		daemon_done (d);
		if (d -> pidfile)
			free (d -> pidfile);
		free (d);
	}
	return NULL;
}/*}}}*/
void
daemon_done (daemon_t *d) /*{{{*/
{
	if (d -> pfvalid) {
		unlink (d -> pidfile);
		d -> pfvalid = false;
	}
}/*}}}*/
bool_t
daemon_lstart (daemon_t *d, log_t *l, logmask_t lmask, const char *lwhat) /*{{{*/
{
	if (d -> background) {
		pid_t	pid;
		mode_t	omask;
		int	n;
		int	fd;
		char	buf[32];
		int	blen;
		
		if ((pid = fork ()) == -1) {
			if (l)
				log_out (l, lmask, lwhat, "Unable to fork (%d, %m)", errno);
			return false;
		} else if (pid > 0)
			exit (0);
		d -> pid = getpid ();
		if (d -> pidfile) {
			omask = umask (0);
			for (n = 0; n < 2; ++n) {
				fd = open (d -> pidfile, O_WRONLY | O_CREAT | O_EXCL, 0644);
				if ((fd == -1) && (! n)) {
					if ((fd = open (d -> pidfile, O_RDONLY)) != -1) {
						blen = read (fd, buf, sizeof (buf) - 1);
						close (fd);
						if (blen > 0) {
							buf[blen] = '\0';
							pid = (pid_t) atol (buf);
							if ((pid > 0) && (kill (pid, 0) == -1) && (errno == ESRCH))
								unlink (d -> pidfile);
						}
						fd = -1;
					}
				}
			}
			umask (omask);
			if (fd == -1) {
				if (l)
					log_out (l, lmask, lwhat, "Unable to create pidfile %s, maybe an instance is already running?", d -> pidfile);
				return false;
			}
			d -> pfvalid = true;
			blen = sprintf (buf, "%10ld\n", (long) d -> pid);
			if (write (fd, buf, blen) != blen)
				d -> pfvalid = false;
			close (fd);
			if (! d -> pfvalid) {
				unlink (d -> pidfile);
				if (l)
					log_out (l, lmask, lwhat, "Failed to write pidfile %s, maybe disk is full?", d -> pidfile);
				return false;
			}
		}
	}
	if (d -> detach) {
		int	n;
		int	fd;

		umask (0);
		for (n = 0; n >= 0; ++n)
			if ((close (n) == -1) && (errno == EBADF))
				break;
		if (setsid () == -1) {
			if (l)
				log_out (l, lmask, lwhat, "Unable to set session (%d, %m)", errno);
			return false;
		}
		if (((fd = open (_PATH_DEVNULL, O_RDWR)) != 0) ||
		    (dup (fd) != 1) ||
		    (dup (fd) != 2)) {
			if (l)
				log_out (l, lmask, lwhat, "Unable to open %s propperly (%d, %m)", _PATH_DEVNULL, errno);
			return false;
		}
	}
	return true;
}/*}}}*/
コード例 #25
0
ファイル: main.cpp プロジェクト: ndrgrimm/Spiedo_PC
int main(int argc, char** argv){
  
  
  QCoreApplication app(argc, argv);
  QDateTime logTime=QDateTime::currentDateTime();
  
  
  QTextStream standard_out(stdout);
  QTextStream standard_in(stdin);
  QTextStream file_out(stdout);
  QFile logFile(".spiedo.log");
  logFile.open(QIODevice::WriteOnly|QIODevice::Append);
  QTextStream log_out(&logFile);
  log_out << QObject::tr("####### - %1 - #######").arg( logTime.toString() )<< endl;
  
  
  
  
  QSerialPort * SerialSelected=Connection();
  if( SerialSelected == 0 )  return 1;
  ConfigurePort(SerialSelected);
  
  standard_out << QObject::tr("Serial is Configured") << endl;
  
  
  
  
  
  if( !SerialSelected->open(QIODevice::ReadWrite) ) {
    standard_out << QObject::tr(" Failed to open port %1, error: %2").arg(SerialSelected->portName()).arg(SerialSelected->errorString()) << endl;
    return 1;
    
  }else{
  standard_out << QObject::tr("Serial is open.") << endl;
  }
  
  SerialSelected->setRequestToSend(true);
  SerialSelected->setRequestToSend(false);
  
  standard_out << QObject::tr("Serial is Configuration:") << endl
               << QObject::tr("Baud rate: ") <<   SerialSelected->baudRate()  << endl
	       << QObject::tr("DataBit: ") <<   SerialSelected->dataBits() << endl
	       << QObject::tr("Parity: ") << ( SerialSelected->parity() )<< endl
               << QObject::tr("Stop Bits: ") << ( SerialSelected->stopBits() )<< endl
	       << QObject::tr("FlowControl:  ") << ( SerialSelected->flowControl() )<< endl
	       
	       ;
  SerialSelected->setRequestToSend(true);
  SerialSelected->setRequestToSend(false);

         
  
  QThread::sleep(2);
  
  char buf[64];                                                                    
  qint64 leghtbuf=0;
  while( ( SerialSelected->waitForReadyRead(10000) ) ){
    
    if( SerialSelected->canReadLine() ){
      leghtbuf=SerialSelected->readLine(buf,sizeof(buf));
      standard_out << buf << endl;
      if( leghtbuf >= 8 ) break;
      
    }
    standard_out << QObject::tr("Waiting for sketchCode") << endl;

  }
  
  if( leghtbuf == 0 ){
   standard_out << QObject::tr("Error: %1").arg(SerialSelected->errorString() ) << endl
		<< QObject::tr(" No sketchCode :(") << endl;
   return 1;
  }else{
    standard_out << QObject::tr("SketchCode recived!") << endl
		 << QObject::tr(" Code: %1 ").arg(buf) << endl
 		 << QObject::tr("Is it correct[Y/n]?\n>>") << flush
 		 ;
  }
  QString tmp;
  tmp=standard_in.readLine();
  if(  tmp[0] == 'n' ) return 0;
  SerialSelected->write("~");
  SerialSelected->flush();
  SerialSelected->waitForReadyRead(1000);
  SerialSelected->readAll();

  standard_out << QObject::tr("HandShake Terminate.") << endl;
  
  
  
  QByteArray Data;
  QByteArray dataBuffer;
  QString nameFile;
  QFile LogMisure;
  char command=' ';
  bool exit=false;
  
  
  standard_out << QObject::tr("Controllo della Seriale:") << endl
		     << QObject::tr("\t[r] Campiona per 1000 volte e restiusce la seguente stringa:") << endl
		     << QObject::tr("\t\t dutyCicle:Mean:Sigma") << endl
		     << QObject::tr("\t[w] Modifica il duty Cicle") << endl
		     << QObject::tr("\t[a] Fa una scansione completa sul duty Cicle da 0 a 255\n")
		     << QObject::tr("\t\t eseguendo ogni volta la lettura( vedi [r] )")<< endl
		     << QObject::tr("\t[t] Acquisisce misure raw dal fotodiodo ad intervalli regolari\n"
				    "\t\trestituendo ad ogni misura la stringa:\n\t\t\tclock:rawMeasure#\n"
				    "\t\tdove il clock è il tempo trascorso tra l'ultimo reset e la \n"
				    "\t\tmisura rawMeasure, espresso in microsecondi\n" ) << flush
		     << QObject::tr("\t[h] restituisce questo OutPut") << endl
		     << QObject::tr("\t[s] Salva su File") << endl
		     << QObject::tr("\t[q] Salva  Esce") << endl
		     ;
  SerialSelected->write("w");
  SerialSelected->flush();
  SerialSelected->write("0");
  SerialSelected->flush();
  
  
  
  while(true){
    standard_out << ">>" << flush;
    standard_in >> command;
    switch(command){
      case 'r':
	SerialSelected->write("r");
	SerialSelected->flush();
	SerialSelected->clear();
	
	while( ( SerialSelected->waitForReadyRead(10000) ) ){
    
	  if( SerialSelected->canReadLine() ){
	   
	    dataBuffer = SerialSelected->readAll();
	    standard_out << dataBuffer << flush;
	    log_out << QObject::tr("[r]:\n") << dataBuffer << flush;
	    dataBuffer.clear();
	    break;
	  }
	}
	SerialSelected->clear();
	SerialSelected->readAll();

        break;
	
      case 'w':
	SerialSelected->write("w");
	SerialSelected->flush();
	standard_out << QObject::tr("Inserire il valore della duty Cicle\n>>") << flush;
	standard_in >> tmp;
	SerialSelected->write(tmp.toStdString().c_str());
	SerialSelected->flush();
	SerialSelected->readAll();
	break;
	
	
	
      case 'a':
        SerialSelected->write("a");
	SerialSelected->flush();
	SerialSelected->clear();

	Data.append("#").append(logTime.toString("ddMMyyyy hhmmss") ).append("\n");
	Data.append("#Scanning on dutyCicle\n#duty\tmean\tsigma\n");
	{
	  QByteArray tmp_data;
	  bool breakWhile=false;
	  while( ( SerialSelected->waitForReadyRead(-1) ) ){
	      tmp_data.clear();
	      tmp_data.append( SerialSelected->readAll() );

	      
	      if( tmp_data.contains('$') ){
		tmp_data.remove( tmp_data.indexOf('$'),1 );
		standard_out << "ora esco" << endl;

		breakWhile=true;
	      }
	      tmp_data.replace(':','\t');
	      tmp_data.replace('%','\n');
	      standard_out << tmp_data << flush;
	      Data.append(tmp_data);
	      
	      
	      if( breakWhile ) break;
	  }
	}
	SerialSelected->readAll();
	
	break;
	
      case 't':
	SerialSelected->write("t");
	SerialSelected->flush();
	SerialSelected->clear();
	
	Data.append("#").append(logTime.toString("ddMMyyyy hhmmss") ).append("\n");
	Data.append("#Acquire ");
	standard_out << QObject::tr("Inserire il numero di misure che si vuole fare\n>>") << flush;
	standard_in >> tmp;
	SerialSelected->write(tmp.toStdString().c_str());
	SerialSelected->flush();
	
	Data.append(" measure\n#time\tMeasure\n");
	{
	  QByteArray tmp_data;
	  bool breakWhile=false;
	  while( ( SerialSelected->waitForReadyRead(10000) ) ){
	      standard_out << "dentro la lettura" << endl;
	      tmp_data.clear();
	      tmp_data.append( SerialSelected->readAll() );
	      
	      if( tmp_data.contains('$') ){
		standard_out << "ora esco" << endl;
		breakWhile=true;
	      }
	      tmp_data.replace(':','\t');
	      tmp_data.replace('%','\n');
	      tmp_data.replace('$','\n');
	      Data.append(tmp_data);
	      if( breakWhile ) break;
	  }
	}
	SerialSelected->readAll();
	break;
      case 's':
	save:
	if ( Data.isEmpty() ){
	  standard_out << QObject::tr("Nothing to save") << endl;
	  break;
	}
	standard_out << QObject::tr("Nome del file: ") << flush;
	
	standard_in >> nameFile;
	LogMisure.setFileName(nameFile);
	LogMisure.open(QIODevice::WriteOnly|QIODevice::Append);
	log_out << QObject::tr("Saving data in %1/ \b%2").arg( QDir::currentPath() ).arg( LogMisure.fileName() )  << endl;

	
	
	file_out.setDevice(&LogMisure);

	
	file_out << Data << flush;
	file_out.device()->close();
	Data.clear();
	break;
	
	
      case 'q':
	SerialSelected->write("q");
	SerialSelected->flush();
	SerialSelected->clear();

	exit=true;
	goto save;
	
	break;
	
      case 'h':
	standard_out << QObject::tr("Controllo della Seriale:") << endl
		     << QObject::tr("\t[r] Campiona per 1000 volte e restiusce la seguente stringa:") << endl
		     << QObject::tr("\t\t dutyCicle:Mean:Sigma") << endl
		     << QObject::tr("\t[w] Modifica il duty Cicle") << endl
		     << QObject::tr("\t[a] Fa una scansione completa sul duty Cicle da 0 a 255\n")
		     << QObject::tr("\t\teseguendo ogni volta la lettura( vedi [r] )")<< endl
		     << QObject::tr("\t[h] restituisce questo OutPut") << endl
		     << QObject::tr("\t[t] Acquisisce misure raw dal fotodiodo ad intervalli regolari\n"
				    "\t\trestituendo ad ogni misura la stringa:\n\t\t\tclock:rawMeasure#\n"
				    "\t\tdove il clock è il tempo trascorso tra l'ultimo reset e la \n"
				    "\t\tmisura raw Measure, espresso in microsecondi\n" ) << flush
		     << QObject::tr("\t[s] Salva su File") << endl
		     << QObject::tr("\t[q] Salva  Esce") << endl
		     ;
	break;
      default:
	if(exit) break;
    }
    if(exit) break;
    
    
  }
  return 0;
}
コード例 #26
0
ファイル: upgradeapp.cpp プロジェクト: shengang1006/xxc2hd
int upgradeapp::device_update_data(char * result, int length){
	if(length <= 0){
		log_out(log_warn, "device_update_data:receive data length is %d\n", length);
		return -1;
	}

	cJSON * json = cJSON_Parse(result);
	if(!json){
		log_out(log_error, "device_update_data:invalid json %s\n", result);
		cJSON_Delete(json);
		return -1;
	}

	cJSON * jscode = cJSON_GetObjectItem(json, "code");
	cJSON * jsmessage = cJSON_GetObjectItem(json, "message");
	cJSON * jsdata = cJSON_GetObjectItem(json, "data");
	if(!jscode || jscode->type != cJSON_Number ||
	   !jsmessage || jsmessage->type != cJSON_String ||
	   !jsdata){
		log_out(log_error, "device_update_data::invalid json %s\n", result);
		cJSON_Delete(json);
		return -1;
	}

	if(jscode->valueint != 0){
		log_out(log_error, "device_update_data:: error code %d\n", jscode->valueint);
		cJSON_Delete(json);
		return -1;
	}

	int count = cJSON_GetArraySize(jsdata);
	log_out(log_debug, "device_update_data::device count %d\n", count);

	for(int k = 0; k < count; k++){
		cJSON * jsdev = cJSON_GetArrayItem(jsdata, k);
		cJSON * jsstatus = cJSON_GetObjectItem(jsdev, "status");
		if(!jsstatus || jsstatus->type != cJSON_Number){
			continue;
		}
		if(jsstatus->valueint){
			continue;
		}

		cJSON * jssn = cJSON_GetObjectItem(jsdev, "ulusn");
		cJSON * jsver = cJSON_GetObjectItem(jsdev, "target_ver");
		cJSON * jsforce = cJSON_GetObjectItem(jsdev, "force");
		cJSON * jsurl = cJSON_GetObjectItem(jsdev, "url");
		cJSON * jsmiss_id = cJSON_GetObjectItem(jsdev, "mission_id");

		cJSON * jstype = cJSON_GetObjectItem(jsdev, "check_type");
		cJSON * jsvalue = cJSON_GetObjectItem(jsdev, "check_value");
		cJSON * jssize = cJSON_GetObjectItem(jsdev, "size");

		if(!jsforce || jsforce->type != cJSON_Number ||
		    !jsver || jsver->type != cJSON_String ||
			!jssn || jssn->type != cJSON_String ||
			!jsurl || jsurl->type != cJSON_String ||
			!jsmiss_id || jsmiss_id->type != cJSON_Number ||
			!jstype || jstype->type != cJSON_String ||
			!jsvalue || jsvalue->type != cJSON_String ||
			!jssize || jssize->type != cJSON_Number){
			continue;
		}

		std::map<strkey_t, dev_state>::iterator it = m_devmap.find(jssn->valuestring);
		if(it != m_devmap.end()){
			it->second.mission_id = jsmiss_id->valueint;

			if(jsforce->valueuint == e_force && it->second.line_state == em_online && (jsver->valuestring != it->second.version)
					&& it->second.upgrade_state != e_upgrading){
				char identify[512] = {0};
				sprintf(identify, "{\"sn\":\"%s\",\"url\":\"%s\",\"check\":{\"type\":\"%s\",\"value\":\"%s\",\"size\":%d}}",
						it->first.c_str(), jsurl->valuestring, jstype->valuestring, jsvalue->valuestring, jssize->valueint);
				post_req(it->second.con, start_update_req, identify);
				it->second.upgrade_state = e_upgrading;			

				log_out(log_debug, "device_update_data::post data to mgrserver: %s\n", identify);

				char buf[512] = {0};
				sprintf(buf, "{\"platform\":\"device\",\"sn\":\"%s\",\"version\":\"%s\",\"mission_id\":%d,\"status\":%d,\"time\":%d}", 
						it->first.c_str(), it->second.version.c_str(), it->second.mission_id, e_upgrading, (int)time(NULL));
				char result[128 * 128] = {0};
				if(post(gs_svr_data.m_api_upgrade_status, buf, strlen(buf), result, sizeof(result)) < 0){
				//	log_out(log_error, "device_update_data:post status fail\n");	
					//	return -1;
				}
				log_out(log_debug, "device_update_data:post status %s\n", buf);
			}
			else{
				log_out(log_warn, "device_update_data:: device(%s) offline or optional(%u) or upgrading or same version\n", jssn->valuestring, jsforce->valueuint);
			}
		}
		else{
			log_out(log_warn, "device_update_data:: invalid device(%s)\n", jssn->valuestring);
		}
	}
	cJSON_Delete(json);
	return 0;
}
コード例 #27
0
ファイル: upgradeapp.cpp プロジェクト: shengang1006/xxc2hd
int upgradeapp::device_update_data(char * result, int length){
	if(length <= 0){
		log_out(log_warn, "device_update_data:receive data length is %d\n", length);
	}

	cJSON * json = cJSON_Parse(result);
	if(!json){
		log_out(log_error, "device_update_data:invalid json %s\n", result);
		return -1;
	}

	cJSON * jscode = cJSON_GetObjectItem(json, "code");
	cJSON * jsmessage = cJSON_GetObjectItem(json, "message");
	cJSON * jsdata = cJSON_GetObjectItem(json, "data");
	if(!jscode || jscode->type != cJSON_Number ||
			!jsmessage || jsmessage->type != cJSON_String ||
			!jsdata){
		cJSON_Delete(json);
		log_out(log_error, "device_update_data::invalid json %s\n", result);
		return -1;
	}

	if(jscode->valueint != 0){
		log_out(log_error, "device_update_data::code %d\n", jscode->valueint);
		cJSON_Delete(json);
		return -1;
	}

	cJSON * jslst = cJSON_GetObjectItem(jsdata, "upgrade");
	if(!jslst){
		log_out(log_warn, "device_update_data::no devices\n");
		cJSON_Delete(json);
		return -1;
	}

	int count = cJSON_GetArraySize(jslst);
	log_out(log_debug, "device_update_data::device count %d\n", count);

	for(int k = 0; k < count; k++){
		cJSON * jsdev = cJSON_GetArrayItem(jslst, k);

		cJSON * jsid = cJSON_GetObjectItem(jsdev, "device_id");
		uint dev = jsid->valueuint;
		cJSON * jsver = cJSON_GetObjectItem(jsdev, "version");
		cJSON * jsforce = cJSON_GetObjectItem(jsdev, "force");
		cJSON * jsurl = cJSON_GetObjectItem(jsdev, "url");
		cJSON * jsver_id = cJSON_GetObjectItem(jsdev, "version_id");

		cJSON * jscheck = cJSON_GetObjectItem(jsdev, "check");
		cJSON * jstype = cJSON_GetObjectItem(jscheck, "type");
		cJSON * jsvalue = cJSON_GetObjectItem(jscheck, "value");
		cJSON * jssize = cJSON_GetObjectItem(jscheck, "size");

		if(!jsforce || jsforce->type != cJSON_Number ||
				!jsver || jsver->type != cJSON_String ||
				!jsurl || jsurl->type != cJSON_String ||
				!jsid || jsid->type != cJSON_Number ||
				!jsver_id || jsver_id->type != cJSON_Number ||
				!jscheck || !jstype || jstype->type != cJSON_String ||
				!jsvalue || jsvalue->type != cJSON_String ||
				!jssize || jssize->type != cJSON_Number){
			log_out(log_error, "start_update_req::invalid json %s\n", jsdev->valuestring);
			continue;
		}

		std::map<uint, dev_state>::iterator it = m_devmap.find(dev);
		if(it != m_devmap.end()){
			it->second.version_id = jsver_id->valueuint;

			if(jsforce->valueuint == e_force && it->second.line_state == em_online){	
				char identify[512] = {0};
				sprintf(identify, "{\"device_id\":%u,\"url\":\"%s\",\"check\":{\"type\":\"%s\",\"value\":\"%s\",\"size\":%d}}",
						it->first, jsurl->valuestring, jstype->valuestring, jsvalue->valuestring, jssize->valueint);
				post_req(it->second.con, start_update_req, identify);
				it->second.upgrade_state = e_upgrading;			
				log_out(log_warn, "device_update_data:: mgrserver: %s\n", identify);

				char buf[512] = {0};
				sprintf(buf, "msg={\"platform\":\"device\",\"data\":[{\"device_id\":%u,\"version_id\":%u,\"status\":%d}]}", 
						it->first, it->second.version_id, e_upgrading);
				log_out(log_debug, "device_update_data:post status %s\n", buf);
				char result[128 * 128] = {0};
				if(post(m_api_upgrade_status, buf, strlen(buf), result, sizeof(result)) < 0){
					log_out(log_error, "device_update_data:post status fail\n");	
				}
			}
		}
		else{
			log_out(log_warn, "device_update_data:: invalid device(%u)\n", dev);
		}
	}
	cJSON_Delete(json);
	return 0;
}
コード例 #28
0
ファイル: svrapp.cpp プロジェクト: shengang1006/xxc2hd
int svrapp::login_mgr_ack(param_list * pl){
	log_out(log_debug, "login_mgr_ack::%s\n", pl->content);
	return 0;
}
コード例 #29
0
ファイル: util.c プロジェクト: guaneryu/e2fsprogs
void print_resource_track(e2fsck_t ctx, const char *desc,
			  struct resource_track *track, io_channel channel)
{
#ifdef HAVE_GETRUSAGE
	struct rusage r;
#endif
#ifdef HAVE_MALLINFO
	struct mallinfo	malloc_info;
#endif
	struct timeval time_end;

	if ((desc && !(ctx->options & E2F_OPT_TIME2)) ||
	    (!desc && !(ctx->options & E2F_OPT_TIME)))
		return;

	e2fsck_clear_progbar(ctx);
	gettimeofday(&time_end, 0);

	if (desc)
		log_out(ctx, "%s: ", desc);

#ifdef HAVE_MALLINFO
#define kbytes(x)	(((unsigned long)(x) + 1023) / 1024)

	malloc_info = mallinfo();
	log_out(ctx, _("Memory used: %luk/%luk (%luk/%luk), "),
		kbytes(malloc_info.arena), kbytes(malloc_info.hblkhd),
		kbytes(malloc_info.uordblks), kbytes(malloc_info.fordblks));
#else
	log_out(ctx, _("Memory used: %lu, "),
		(unsigned long) (((char *) sbrk(0)) -
				 ((char *) track->brk_start)));
#endif
#ifdef HAVE_GETRUSAGE
	getrusage(RUSAGE_SELF, &r);

	log_out(ctx, _("time: %5.2f/%5.2f/%5.2f\n"),
		timeval_subtract(&time_end, &track->time_start),
		timeval_subtract(&r.ru_utime, &track->user_start),
		timeval_subtract(&r.ru_stime, &track->system_start));
#else
	log_out(ctx, _("elapsed time: %6.3f\n"),
		timeval_subtract(&time_end, &track->time_start));
#endif
#define mbytes(x)	(((x) + 1048575) / 1048576)
	if (channel && channel->manager && channel->manager->get_stats) {
		io_stats delta = 0;
		unsigned long long bytes_read = 0;
		unsigned long long bytes_written = 0;

		if (desc)
			log_out(ctx, "%s: ", desc);

		channel->manager->get_stats(channel, &delta);
		if (delta) {
			bytes_read = delta->bytes_read - track->bytes_read;
			bytes_written = delta->bytes_written -
				track->bytes_written;
		}
		log_out(ctx, "I/O read: %lluMB, write: %lluMB, "
			"rate: %.2fMB/s\n",
			mbytes(bytes_read), mbytes(bytes_written),
			(double)mbytes(bytes_read + bytes_written) /
			timeval_subtract(&time_end, &track->time_start));
	}
}
コード例 #30
0
ファイル: ac.c プロジェクト: ajinkya93/OpenBSD
int
ac(FILE	*fp)
{
	struct utmp_list *lp, *head = NULL;
	struct utmp usr;
	struct tm *ltm;
	time_t secs = 0, prev = 0;
	int day = -1;

	while (fread((char *)&usr, sizeof(usr), 1, fp) == 1) {
		if (!FirstTime)
			FirstTime = usr.ut_time;
		if (usr.ut_time < prev)
			continue;	/* broken record */
		prev = usr.ut_time;
		if (Flags & AC_D) {
			ltm = localtime(&usr.ut_time);
			if (day >= 0 && day != ltm->tm_yday) {
				day = ltm->tm_yday;
				/*
				 * print yesterday's total
				 */
				secs = usr.ut_time;
				secs -= ltm->tm_sec;
				secs -= 60 * ltm->tm_min;
				secs -= 3600 * ltm->tm_hour;
				show_today(Users, head, secs);
			} else
				day = ltm->tm_yday;
		}
		switch(*usr.ut_line) {
		case '|':
			secs = usr.ut_time;
			break;
		case '{':
			secs -= usr.ut_time;
			/*
			 * adjust time for those logged in
			 */
			for (lp = head; lp != NULL; lp = lp->next)
				lp->usr.ut_time -= secs;
			break;
		case '~':			/* reboot or shutdown */
			head = log_out(head, &usr);
			FirstTime = usr.ut_time; /* shouldn't be needed */
			break;
		default:
			/*
			 * if they came in on a pseudo-tty, then it is only
			 * a login session if the ut_host field is non-empty
			 */
			if (*usr.ut_name) {
				if (strncmp(usr.ut_line, "tty", 3) != 0 ||
				    strchr("pqrstuvwxyzPQRST", usr.ut_line[3]) != NULL ||
				    *usr.ut_host != '\0')
					head = log_in(head, &usr);
			} else
				head = log_out(head, &usr);
			break;
		}
	}
	(void)fclose(fp);
	if (!(Flags & AC_W))
		usr.ut_time = time(NULL);
	(void)strlcpy(usr.ut_line, "~", sizeof usr.ut_line);

	if (Flags & AC_D) {
		ltm = localtime(&usr.ut_time);
		if (day >= 0 && day != ltm->tm_yday) {
			/*
			 * print yesterday's total
			 */
			secs = usr.ut_time;
			secs -= ltm->tm_sec;
			secs -= 60 * ltm->tm_min;
			secs -= 3600 * ltm->tm_hour;
			show_today(Users, head, secs);
		}
	}
	/*
	 * anyone still logged in gets time up to now
	 */
	head = log_out(head, &usr);

	if (Flags & AC_D)
		show_today(Users, head, time(NULL));
	else {
		if (Flags & AC_P)
			show_users(Users);
		show("total", Total);
	}
	return 0;
}