Exemple #1
0
void init_cfgparser(unsigned char st[]){ 

	unsigned char *s;
	unsigned int phn,ann,dgn,num_pmu;
	int i,j,dgchannels;
	struct cfg_frame *cfg;
	struct channel_names *cn;


	/******************** PARSING BEGINGS *******************/

	cfg = malloc(sizeof(struct cfg_frame));

	if(!cfg) {

		printf("Not enough memory for cfg\n");
	}

	s = st;

	/* Memory Allocation Begins - Allocate memory to framesize */
	cfg->framesize = malloc(3*sizeof(unsigned char));
	if(!cfg->framesize) {
		printf("Not enough memory for cfg->framesize\n");
	}

	// Allocate memory to idcode
	cfg->idcode = malloc(3*sizeof(unsigned char));
	if(!cfg->idcode) {
		printf("Not enough memory for cfg->framesize\n");
	}

	// Allocate memory to soc
	cfg->soc = malloc(5*sizeof(unsigned char));
	if(!cfg->soc) {
		printf("Not enough memory for cfg->soc\n");
	}

	// Allocate memory to fracsec
	cfg->fracsec = malloc(5*sizeof(unsigned char));
	if(!cfg->fracsec) {
		printf("Not enough memory for cfg->fracsec\n");
	}

	// Allocate memory to time_base
	cfg->time_base = malloc(5*sizeof(unsigned char));
	if(!cfg->time_base) {
		printf("Not enough memory for cfg->time_base\n");
	}

	// Allocate memory to num_pmu
	cfg->num_pmu = malloc(3*sizeof(unsigned char));
	if(!cfg->num_pmu) {
		printf("Not enough memory for cfg->num_pmu\n");
	}

	// Allocate memory to data_rate
	cfg->data_rate = malloc(3*sizeof(unsigned char));
	if(!cfg->data_rate) {
		printf("Not enough memory for cfg->data_rate\n");
	}

	// Skip the sync word
	s = s + 2;	

	// Separate the FRAME SIZE
	copy_cbyc (cfg->framesize,(unsigned char *)s,2);
	cfg->framesize[2]='\0';
	s = s + 2;

	//SEPARATE IDCODE
	copy_cbyc (cfg->idcode,(unsigned char *)s,2);
	cfg->idcode[2]='\0';
	int id = to_intconvertor(cfg->idcode);
	printf("ID Code %d\n",id);
	s = s + 2;

	//SEPARATE SOC
	copy_cbyc (cfg->soc,(unsigned char *)s,4);
	cfg->soc[4]='\0';
	s = s + 4;

	//SEPARATE FRACSEC
	copy_cbyc (cfg->fracsec,(unsigned char *)s,4);
	cfg->fracsec[4]='\0';
	s = s + 4;

	//SEPARATE TIMEBASE
	copy_cbyc (cfg->time_base,(unsigned char *)s,4);
	cfg->time_base[4]='\0';
	s = s + 4;

	//SEPARATE PMU NUM
	copy_cbyc (cfg->num_pmu,(unsigned char *)s,2);
	cfg->num_pmu[2]='\0';
	s = s + 2;	

	num_pmu = to_intconvertor(cfg->num_pmu);
	printf("Number of PMU's = %d.\n",num_pmu);

	// Allocate Memeory For Each PMU
	cfg->pmu = malloc(num_pmu* sizeof(struct for_each_pmu *));
	if(!cfg->pmu) {
		printf("Not enough memory pmu[][]\n");
		exit(1);
	}

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

		cfg->pmu[i] = malloc(sizeof(struct for_each_pmu));
	}

	j = 0;

	///WHILE EACH PMU IS HANDLED
	while(j<num_pmu) {

		// Memory Allocation for stn
		cfg->pmu[j]->stn = malloc(17*sizeof(unsigned char));
		if(!cfg->pmu[j]->stn) {
			printf("Not enough memory cfg->pmu[j]->stn\n");
			exit(1);
		}

		// Memory Allocation for idcode
		cfg->pmu[j]->idcode = malloc(3*sizeof(unsigned char));
		if(!cfg->pmu[j]->idcode) {
			printf("Not enough memory cfg->pmu[j]->idcode\n");
			exit(1);
		}

		// Memory Allocation for format
		cfg->pmu[j]->data_format = malloc(3*sizeof(unsigned char));
		if(!cfg->pmu[j]->data_format) {
			printf("Not enough memory cfg->pmu[j]->data_format\n");
			exit(1);
		}

		// Memory Allocation for phnmr
		cfg->pmu[j]->phnmr = malloc(3*sizeof(unsigned char));
		if(!cfg->pmu[j]->phnmr) {
			printf("Not enough memory cfg->pmu[j]->phnmr\n");
			exit(1);
		}

		// Memory Allocation for annmr
		cfg->pmu[j]->annmr = malloc(3*sizeof(unsigned char));
		if(!cfg->pmu[j]->annmr) {
			printf("Not enough memory cfg->pmu[j]->annmr\n");
			exit(1);
		}

		// Memory Allocation for dgnmr
		cfg->pmu[j]->dgnmr = malloc(3*sizeof(unsigned char));
		if(!cfg->pmu[j]->dgnmr) {
			printf("Not enough memory cfg->pmu[j]->dgnmr\n");
			exit(1);
		}

		// Memory Allocation for fnom
		cfg->pmu[j]->fnom = malloc(3*sizeof(unsigned char));
		if(!cfg->pmu[j]->fnom) {
			printf("Not enough memory cfg->pmu[j]->fnom\n");
			exit(1);
		}

		// Memory Allocation for cfg_cnt
		cfg->pmu[j]->cfg_cnt = malloc(3*sizeof(unsigned char));
		if(!cfg->pmu[j]->cfg_cnt) {
			printf("Not enough memory cfg->pmu[j]->cfg_cnt\n");
			exit(1);
		}

		//SEPARATE STATION NAME
		copy_cbyc (cfg->pmu[j]->stn,(unsigned char *)s,16);
		cfg->pmu[j]->stn[16]='\0';
		s = s + 16;

		//SEPARATE IDCODE		
		copy_cbyc (cfg->pmu[j]->idcode,(unsigned char *)s,2);
		cfg->pmu[j]->idcode[2]='\0';
		s = s + 2;

		//SEPARATE DATA FORMAT		
		copy_cbyc (cfg->pmu[j]->data_format,(unsigned char *)s,2);
		cfg->pmu[j]->data_format[2]='\0';
		s = s + 2;	

		// USE fmt
		unsigned char hex = cfg->pmu[j]->data_format[1];
		hex <<= 4;

		// Extra field has been added to identify polar,rectangular,floating/fixed point	
		cfg->pmu[j]->fmt = malloc(sizeof(struct format));
		if((hex & 0x80) == 0x80) cfg->pmu[j]->fmt->freq = '1'; else cfg->pmu[j]->fmt->freq = '0';
		if((hex & 0x40) == 0x40 ) cfg->pmu[j]->fmt->analog = '1'; else cfg->pmu[j]->fmt->analog = '0';
		if((hex & 0x20) == 0x20) cfg->pmu[j]->fmt->phasor = '1'; else cfg->pmu[j]->fmt->phasor = '0';
		if((hex & 0x10) == 0x10) cfg->pmu[j]->fmt->polar =  '1'; else cfg->pmu[j]->fmt->polar = '0';

		//SEPARATE PHASORS	
		copy_cbyc (cfg->pmu[j]->phnmr,(unsigned char *)s,2);
		cfg->pmu[j]->phnmr[2]='\0';
		s = s + 2;
		phn = to_intconvertor(cfg->pmu[j]->phnmr);

		//SEPARATE ANALOGS			
		copy_cbyc (cfg->pmu[j]->annmr,(unsigned char *)s,2);
		cfg->pmu[j]->annmr[2]='\0';
		s = s + 2;
		ann = to_intconvertor(cfg->pmu[j]->annmr);

		//SEPARATE DIGITALS			
		copy_cbyc (cfg->pmu[j]->dgnmr,(unsigned char *)s,2);
		cfg->pmu[j]->dgnmr[2] = '\0';
		s = s + 2; 
		dgn = to_intconvertor(cfg->pmu[j]->dgnmr);
//		printf("Station %s, CFG consist Phasor = %d, Analogs = %d, and Digitals = %d.\n",cfg->pmu[j]->stn,phn,ann,dgn);

		cn = malloc(sizeof(struct channel_names));
		if(!cn) {
			printf("Not enough memory cn\n");
			exit(1);
		}
		cn->first =  NULL;

		////SEPARATE PHASOR NAMES 
		if(phn != 0){

			cn->phnames = malloc(phn*sizeof(unsigned char*));
			if(!cn->phnames) {
				printf("Not enough memory cfg->pmu[j]->cn->phnames[][]\n");
				exit(1);
			}

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

				cn->phnames[i] = malloc(17*sizeof(unsigned char));
			}

			i = 0;//Index for PHNAMES

			while(i<phn){
				copy_cbyc (cn->phnames[i],(unsigned char *)s,16);
				cn->phnames[i][16] = '\0';        
//				printf("Phnames %s\n",cn->phnames[i]);
				s = s + 16;  
				i++;
			}
		} 

		//SEPARATE ANALOG NAMES
		if(ann!=0){
			cn->angnames = malloc(ann*sizeof(unsigned char*));
			if(!cn->angnames) {
				printf("Not enough memory cfg->pmu[j]->cn->phnames[][]\n");
				exit(1);
			}

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

				cn->angnames[i] = malloc(17*sizeof(unsigned char));
			}

			i=0;//Index for ANGNAMES

			while(i<ann){
				copy_cbyc (cn->angnames[i],(unsigned char *)s,16);
				cn->angnames[i][16]='\0';
//				printf("ANGNAMES %s\n",cn->angnames[i]);
				s =s + 16;  
				i++;			
			}
		}

		i = 0; //Index for number of dgwords
		struct dgnames *q;

		while(i<dgn) {

			struct dgnames *temp1 = malloc(sizeof(struct dgnames));

			temp1->dgn = malloc(16*sizeof(unsigned char *));
			if(!temp1->dgn) {
				printf("Not enough memory temp1->dgn\n");
				exit(1);
			}

			for(dgchannels=0;dgchannels<16;dgchannels++){

				temp1->dgn[dgchannels] = malloc(17*sizeof(unsigned char));
			}

			temp1->dg_next = NULL;

			for(dgchannels=0;dgchannels<16;dgchannels++){

				copy_cbyc (temp1->dgn[dgchannels],(unsigned char *)s,16);
				temp1->dgn[dgchannels][16]='\0';
				s += 16;
//				printf("%s\n",temp1->dgn[dgchannels]);
			}

			if(cn->first == NULL){
				cn->first = q = temp1;
			} else {
				while(q->dg_next!=NULL){
					q = q->dg_next;
				}
				q->dg_next = temp1;			       
			}  
			i++;  
		} //DGWORD WHILE ENDS

		cfg->pmu[j]->cnext = cn;//Assign to pointers

		///PHASOR FACTORS
		if(phn != 0){

			cfg->pmu[j]->phunit = malloc(phn*sizeof(unsigned char*));
			if(!cfg->pmu[j]->phunit) {
				printf("Not enough memory cfg->pmu[j]->phunit[][]\n");
				exit(1);
			}

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

				cfg->pmu[j]->phunit[i] = malloc(5*sizeof(unsigned char));
			}

			i = 0;

			while(i<phn){ //Separate the Phasor conversion factors

				copy_cbyc (cfg->pmu[j]->phunit[i],(unsigned char *)s,4);
				cfg->pmu[j]->phunit[i][4] = '\0';
				s = s + 4;
				i++;
			}
		}//if for PHASOR Factors ends

		//ANALOG FACTORS
		if(ann != 0){

			cfg->pmu[j]->anunit = malloc(ann*sizeof(unsigned char*));
			if(!cfg->pmu[j]->anunit) {
				printf("Not enough memory cfg->pmu[j]->anunit[][]\n");
				exit(1);
			}

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

				cfg->pmu[j]->anunit[i] = malloc(5*sizeof(unsigned char));

			}

			i = 0;

			while(i<ann){ //Separate the Phasor conversion factors
				copy_cbyc (cfg->pmu[j]->anunit[i],(unsigned char *)s,4);
				cfg->pmu[j]->anunit[i][4] = '\0';
				s = s + 4;
				i++;
			}

		} // if for ANALOG Factors ends

		if(dgn != 0){

			cfg->pmu[j]->dgunit = malloc(dgn*sizeof(unsigned char*));
			if(!cfg->pmu[j]->dgunit) {
				printf("Not enough memory cfg->pmu[j]->dgunit[][]\n");
				exit(1);
			}

			for (i = 0; i < dgn; i++) {
				cfg->pmu[j]->dgunit[i] = malloc(5*sizeof(unsigned char));
			}

			i = 0;

			while(i<dgn){ //Separate the Phasor conversion factors

				copy_cbyc (cfg->pmu[j]->dgunit[i],(unsigned char *)s,4);
				cfg->pmu[j]->dgunit[i][4] = '\0';
				s = s + 4;
				i++;
			}
		} //if for Digital Words Factors ends

		copy_cbyc (cfg->pmu[j]->fnom,(unsigned char *)s,2);
		cfg->pmu[j]->fnom[2]='\0';
		s = s + 2;

		copy_cbyc (cfg->pmu[j]->cfg_cnt,(unsigned char *)s,2);
		cfg->pmu[j]->cfg_cnt[2] = '\0';
		s = s + 2;	
		j++;
	}//While for PMU number ends

	copy_cbyc (cfg->data_rate,(unsigned char *)s,2);
	cfg->data_rate[2] = '\0';
	cfg->cfgnext = NULL;

	if (cfgfirst == NULL)  {
		cfgfirst = cfg;	
	} else {

		struct cfg_frame *t=cfgfirst;
		while(t->cfgnext != NULL){
			t = t->cfgnext;
		}
		t->cfgnext = cfg;
	}
} 
void* UL_udp(){

	// KK Design

	/* 1. Design and handle the requests from SPDCs and Peer PDCs that indicate model updates and model violations respectively
	   2. see if the updated model from SPDC is received. Accordingly set the flags and update in the MapPMUToPhasor the alpha and averagefreq.
	   3. See if the peer PDC sends the model violation trigger
	   4. Maintain soc and fracsec of the latest PMU frames dispatched that can identify if the data is in the database
	   5. Create data frame from the data fetched from in - Memory db if the data has already been dispatched from iPDC
	*/

	/* UDP data Received */
	while(1) {
		unsigned char* UL_udp_command = (unsigned char*)malloc(MAXBUFLEN* sizeof(unsigned char)); //My Change

		memset(UL_udp_command,'\0',MAXBUFLEN); //My Change
		
/*		memset(UL_udp_command,'\0',19);*/
		memset(display_buf,'\0',200);

		if ((numbytes = recvfrom(UL_UDP_sockfd,UL_udp_command,MAXBUFLEN-1, 0,(struct sockaddr *)&UL_UDP_addr, (socklen_t *)&UL_UDP_addr_len)) == -1) { 
			// Main if
			perror("recvfrom");
			exit(1);

		} else { /* New datagram has been received */
/*printf("here\n");*/
			int pdc_flag = 0;
			pthread_mutex_lock(&mutex_Upper_Layer_Details);
			struct Upper_Layer_Details *temp_pdc = ULfirst;	
			
			if(ULfirst == NULL) {
/*printf("here1\n");*/
				pdc_flag = 0;				

			} else  {

				while(temp_pdc != NULL ) {
/*printf("here2\n");*/
					if((!strcmp(temp_pdc->ip,inet_ntoa(UL_UDP_addr.sin_addr))) && 
							(!strncasecmp(temp_pdc->protocol,"UDP",3)) && (temp_pdc->port == UDPPORT)) {

						pdc_flag = 1;		
						break;
					} else {

						temp_pdc = temp_pdc->next;
					}									
				}  												
			}

			if(pdc_flag){ 
/*printf("here3\n");*/
				unsigned char c = UL_udp_command[1];
				c <<= 1;
				c >>= 5;	
				temp_pdc->sockfd = UL_UDP_sockfd;

				if(c  == 0x04) { /* Check if it is a command frame from Upper PDC */ 
/*printf("here4\n");*/
					//printf("\nCommand frame Received at iPDC.\n");
					c = UL_udp_command[15];
/*					printf("c = %x\n",c);*/
					if((c & 0x06) == 0x06){ // Received a Query
						if(LPDCApp == true){
							
							struct PMUQueryInfo* temp_query = (struct PMUQueryInfo*)malloc(sizeof(struct PMUQueryInfo));
							unsigned char * index = (unsigned char *)UL_udp_command;
							index += 2; // Skip SYNC
						
							unsigned char framesize[3];
							copy_cbyc(framesize,index,2);
							index += 2; // Skip Framesize
				
							framesize[2] = '\0';
							int frsize = to_intconvertor((unsigned char*)framesize);
						
							unsigned char mpmuid[3];
							copy_cbyc(mpmuid,index,2);
							index += 2;
							mpmuid[2] = '\0';
							temp_query->pmuid = to_intconvertor((unsigned char*)mpmuid);
	
							index += 4; // Skip soc
							index += 4; // Skip fracsec
							index += 2; // Skip Cmdcode
						
							unsigned char apiid[3];
							copy_cbyc(apiid,index,2);
							index += 2;
							apiid[2] = '\0';
							temp_query->api_id = to_intconvertor((unsigned char*)apiid);
						
							unsigned char qid[3];
							copy_cbyc(qid,index,2);
							index += 2;
							qid[2] = '\0';
							temp_query->query_id = to_intconvertor((unsigned char*)qid);
							
/*printf("pmuid = %d, apiid = %d, queryid = %d\n",temp_query->pmuid,temp_query->api_id,temp_query->query_id);				*/
							
							unsigned char invoke_soc[5];
							copy_cbyc(invoke_soc,index,4);
							index += 4;
							invoke_soc[4] = '\0';
							temp_query->invoke_soc = to_long_int_convertor((unsigned char*)invoke_soc);
						
							unsigned char invoke_fracsec[5];
							copy_cbyc(invoke_fracsec,index,4);
							index += 4;
							invoke_fracsec[4] = '\0';
							temp_query->invoke_fracsec = to_long_int_convertor((unsigned char*)invoke_fracsec);
							
							copy_cbyc(temp_query->phasorname,index,16);
							index += 16;
							(temp_query->phasorname)[16] = '\0';
											
							temp_query->phasorNumber = -1;
								
							struct cfg_frame *temp_cfg = cfgfirst;
	
							// Check for the IDCODE in Configuration Frame
							while(temp_cfg != NULL){
/*printf("idcode = %d\n",to_intconvertor(temp_cfg->idcode));*/
								if(temp_query->pmuid == to_intconvertor(temp_cfg->idcode)) {
/*printf("here\n");	*/
									int phnmr = to_intconvertor(temp_cfg->pmu[0]->phnmr);
/*printf("phnmr = %d\n",phnmr);	*/
									int i;
									for(i = 0;i<phnmr;i++){
/*printf("(%s) == (%s)\n",temp_cfg->pmu[0]->cnext->phnames[i],temp_query->phasorname);*/
										if(!strcmp(temp_cfg->pmu[0]->cnext->phnames[i],temp_query->phasorname)){
/*printf("inside\n");*/
											temp_query->phasorNumber = i;
											break;
										}
									}
									break;
								} else {

									temp_cfg = temp_cfg->cfgnext;
								}
							}
						
							temp_query->spdc = temp_pdc;
							
							c = UL_udp_command[14];

							if((c & 0x01) == 0x01){ // Received a common Query for result
/*								printf("Received a common Query for result\n");*/
								
/*								printf("fsize = %d, numbyte = %d, Monitored PMUID = %d, SOC = %ld, FRACSEC = %ld, APIid = %d, QueryId = %d, Phasorname = %s, PhasorNo. = %d. \n",frsize,numbytes, temp_query->pmuid,temp_query->invoke_soc,temp_query->invoke_fracsec,temp_query->api_id,temp_query->query_id,temp_query->phasorname,temp_query->phasorNumber);*/
								
/*								writeTimeToLog(5,temp_query->pmuid,temp_query->invoke_soc,temp_query->invoke_fracsec);*/
								pthread_attr_t attr;
								pthread_attr_init(&attr);
								int err;
								/* In  the detached state, the thread resources are immediately freed when it terminates, but
								   pthread_join(3) cannot be used to synchronize on the thread termination. */
								if((err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED))) {

									perror(strerror(err));
									exit(1);
								}																																										     	  
								/* Shed policy = SCHED_FIFO (realtime, first-in first-out) */
								if((err = pthread_attr_setschedpolicy(&attr,SCHED_FIFO))) {

									perror(strerror(err));		     
									exit(1);
								}  

								pthread_t t;
								if((err = pthread_create(&t,&attr,execute_query,(void *)temp_query))) {
									perror(strerror(err));		     
									exit(1);
								}
							
							}
							else{	// Received a filter Query
/*								printf("Received a Filter Query\n");*/
														
								unsigned char slope[5];
								copy_cbyc(slope,index,4);
								index += 4;
								slope[4] = '\0';
								temp_query->bounds_slope = c2f_ieee((unsigned char*)slope);
						
								unsigned char dlb[5];
								copy_cbyc(dlb,index,4);
								index += 4;
								dlb[4] = '\0';
								temp_query->displace_lb = c2f_ieee((unsigned char*)dlb);

								unsigned char dub[5];
								copy_cbyc(dub,index,4);
								index += 4;
								dub[4] = '\0';
								temp_query->displace_ub = c2f_ieee((unsigned char*)dub);
												
								char key[16];
								sprintf(key,"%d",temp_query->pmuid);
/*	printf("second pmuid = %d, apiid = %d, queryid = %d\n",temp_query->pmuid,temp_query->api_id,temp_query->query_id);*/
/*	printf("fsize = %d, numbyte = %d, Monitored PMUID = %d, SOC = %ld, FRACSEC = %ld, APIid = %d, QueryId = %d, Phasorname = %s, PhasorNo. = %d, boundslope= %f, displace_lb= %f, displace_ub=%f. \n",frsize,numbytes, temp_query->pmuid,temp_query->invoke_soc,temp_query->invoke_fracsec,temp_query->api_id,temp_query->query_id,temp_query->phasorname,temp_query->phasorNumber,temp_query->bounds_slope,temp_query->displace_lb,temp_query->displace_ub);*/
	
								updateQueryList(key ,temp_query, &hashForPMUQuery);
		
						
						

							}
						}
					}
						
					else if((c & 0x05) == 0x05){ //Send CFg frame to PDC
/*printf("here5\n");*/
						printf("\nCommand frame for CFG Received\n");

						while(root_pmuid != NULL); // Wait till all the status change has been cleared

/*						printf("sockfd = %d,ipaddress = %s\n",temp_pdc->sockfd,inet_ntoa(temp_pdc->pdc_addr.sin_addr));*/

						if(temp_pdc->address_set == 0) {
/*printf("here6\n");*/
							memcpy(&temp_pdc->pdc_addr,&UL_UDP_addr,sizeof(UL_UDP_addr));

						}
						//numbytes = create_cfgframe(cfgfirst);
						//if(angleDiffApp == true && DDS == 3 && LPDCApp == true) {
						if(LPDCApp == true) {
/*printf("here7\n");*/
							numbytes = create_cfgframe(cfgfirst);
						}

						if ((numbytes = sendto (temp_pdc->sockfd,cfgframe, numbytes, 0,
								(struct sockaddr *)&temp_pdc->pdc_addr,sizeof(temp_pdc->pdc_addr)) == -1)) {
/*printf("here8\n");*/
							perror("sendto");

						} else {

							printf("Sent iPDC Configuration Frame\n");
						}
						free(cfgframe);

						temp_pdc->UL_upper_pdc_cfgsent = 1;
						temp_pdc->config_change = 0;

					} else if((c & 0x02) == 0x02) { // if data frame 

						if(temp_pdc->UL_upper_pdc_cfgsent == 1) { // Only if cfg is sent send the data	
/*printf("here9\n");*/
							temp_pdc->UL_data_transmission_off = 0;

						} else {

							printf("Data cannot be sent as CMD for CFG not received\n");

						}			

					} else if ((c & 0x01) == 0x01){

						temp_pdc->UL_data_transmission_off = 1;

					}				  

				} else { /* If it is a frame other than command frame */

					printf("Not a command frame\n");						
				}


			} else { /* If the command frame is not from authentic PDC*/

				printf("Command frame from un-authentic PDC\n");
			}

		} // Main if ends	
		
		free(UL_udp_command);//My change
		pthread_mutex_unlock(&mutex_Upper_Layer_Details);
	} // while ends		
void* connect_pmu_udp(void *temp) {

	int udp_sockfd,port_num,addr_len,yes = 1;
	unsigned char *udp_BUF,*ptr,length[2];
	unsigned int flen;	
	uint16_t cal_crc,frame_crc;


	pthread_attr_t attr;
	pthread_attr_init(&attr);
	int err;

	/* In  the detached state, the thread resources are immediately freed when it terminates, but 
	   pthread_join(3) cannot be used to synchronize on the thread termination. */
	if((err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED))) { 
		 
		perror(strerror(err));	                                        
		exit(1);      
	}								

	/* Shed policy = SCHED_FIFO (realtime, first-in first-out) */
	if((err = pthread_attr_setschedpolicy(&attr,SCHED_FIFO))) { 

		perror(strerror(err));		     
		exit(1);
	}  


	struct sockaddr_in PMU_addr,their_addr;
	struct Lower_Layer_Details *temp_pmu = (struct Lower_Layer_Details *) temp;
	struct Lower_Layer_Details *t ;

	port_num = temp_pmu->port;

	if ((udp_sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
		perror("socket");
		exit(1);
	}

	if (setsockopt(udp_sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
		perror("setsockopt");
		exit(1);
	}

	bzero(&PMU_addr,sizeof(PMU_addr));
	PMU_addr.sin_family = AF_INET;
	PMU_addr.sin_addr.s_addr =  inet_addr(temp_pmu->ip); 
	PMU_addr.sin_port = htons(port_num);
	memset(&(PMU_addr.sin_zero), '\0', 8);   // zero the rest of the struct

	/* Copy the information of Lower Layer PMU/PDC to the node */
	temp_pmu->thread_id = pthread_self();
	bzero(&temp_pmu->llpmu_addr,sizeof(PMU_addr));
	temp_pmu->llpmu_addr.sin_family = AF_INET;
	temp_pmu->llpmu_addr.sin_addr.s_addr =  inet_addr(temp_pmu->ip);  
	temp_pmu->llpmu_addr.sin_port = htons(port_num);
	memset(&(temp_pmu->llpmu_addr.sin_zero), '\0', 8);   // zero the rest of the struct
	temp_pmu->sockfd = udp_sockfd;
	temp_pmu->up = 1;

	/* Add PMU*/
	add_PMU_Node(temp_pmu);	

	udp_BUF = malloc(MAXBUFLEN* sizeof(unsigned char));

	/* Sending Command fro obtaining CFG */
	addr_len = sizeof(struct sockaddr);	
	int n,bytes_read;
	unsigned char *cmdframe = malloc(19);
	cmdframe[18] = '\0';
	create_command_frame(1,temp_pmu->pmuid,(char *)cmdframe);

	if ((n = sendto(udp_sockfd,cmdframe, 18, 0, (struct sockaddr *)&PMU_addr,sizeof(PMU_addr)) == -1)) {

		perror("sendto"); 

	} else {

		free(cmdframe);
	//	printf("%d\n",port_num);
		/* UDP data Received */
		while(1) {

			memset(udp_BUF,'\0',MAXBUFLEN * sizeof(unsigned char));

			bytes_read = recvfrom (udp_sockfd, udp_BUF,MAXBUFLEN-1,0,(struct sockaddr *)&their_addr,(socklen_t *)&addr_len); 				
			if(bytes_read == -1) {

				perror("recvfrom");
				exit(1);

			} else { // New Datagram received
				int id;
				unsigned long soc,fsec;
				char idcode[2],soC[4],fracsec[3];
					
				unsigned char c = udp_BUF[1];
				c <<= 1;
				c >>= 5;

				int flag = 0;
				if(LLfirst == NULL) {
					flag = 0;
				} else {
					t = LLfirst;
					while(t != NULL) {
						if((!strcmp(t->ip,inet_ntoa(their_addr.sin_addr))) && (!strncasecmp(t->protocol,"UDP",3))) {
							flag = 1;
							break;
						} else {
							t = t->next;
						}
					}
				}
				//pthread_mutex_unlock(&mutex_Lower_Layer_Details);

				if(flag) {
					ptr = udp_BUF;
					ptr += 2;
					copy_cbyc(length,ptr,2);
					flen = to_intconvertor(length);
					cal_crc = compute_CRC(udp_BUF,flen-2);
					ptr += flen -4;
					frame_crc = *ptr;
					frame_crc <<= 8;
					frame_crc |= *(ptr + 1);

					if(frame_crc != cal_crc) {

						continue;
					}

					udp_BUF[bytes_read] = '\0';
				if(c == 0x00){
					int indx = bytes_read-8;
					unsigned char temp5[5],*d;
					long int pmusoc, pmufracsec;
			
					d =  udp_BUF;
					d += indx;
			
					//SEPARATE soc
					memset(temp5,'\0',5);
					copy_cbyc (temp5,d,4);
					pmusoc = to_long_int_convertor(temp5);
					d += 4;	

					//SEPARATE fracsec
					memset(temp5,'\0',5);
					copy_cbyc (temp5,d,4);
					pmufracsec = to_long_int_convertor(temp5);
			
					

					ptr = udp_BUF;
					ptr+=4;
					copy_cbyc(idcode,ptr,2);
					ptr+=2;
					copy_cbyc(soC,ptr,4);
					ptr+=5;		
					copy_cbyc(fracsec,ptr,3);
					ptr+=3;		

					id = to_intconvertor(idcode);
					soc= to_long_int_convertor(soC);
					fsec = to_long_int_convertor1(fracsec);
/*					printf("pmusoc %ld pmufracsec %ld\n",pmusoc,pmufracsec);*/
					if(id == 0)
				printf("Pmu Id = %d, SOC = %ld, FRACSEC = %ld\n",id,soc,fsec);
					char code = udp_BUF[14];
					if(SPDCApp == true) {
						if(code == 0x08){
							int t_index;
							//printf("Pmu Id = %d, SOC = %lu %u, FRACSEC = %lu %u\n",id,soc,to_long_int_convertor(soC),fsec,to_long_int_convertor1(fracsec));
							t_index= matchDataFrameTimeToTSBTime_SPDC_No_Update(to_long_int_convertor(soC),to_long_int_convertor1(fracsec));

							//printf("t_index = %d \n",t_index);
							if(t_index == -1)
								printf("Ata Mazi Satkli... \n");
							else if(t_index != 99)
							{

								Analysing(11,id,pmusoc,pmufracsec,t_index);
							}


						}else if(code == 0x07){
							Analysing(65,id,pmusoc,pmufracsec,0);
						}else if(code == 0x09){
							/*							Analysing(22,id,pmusoc,pmufracsec);*/
							app2_Analysing(22,id,soc,fsec,pmusoc,pmufracsec); 
						}
					}else if(LPDCApp == true  && c == 0x00) // Condition ensures lost packet implementation
						//else if(LPDCApp == true)
					{
						char key[16];
						ENTRY entry;
						ENTRY *found;
						sprintf(key,"%d",id);
						entry.key = key;
						hsearch_r( entry, FIND, &found, &(app1->hashForApp1Pmus));
						if(found!=NULL){
					if(IsDelayed == 1 && id == LostPmuId)
							{
								struct pthread_args *args=(struct pthread_args*)malloc(sizeof(struct pthread_args));
								args->udp_BUF = malloc(bytes_read * sizeof(unsigned char));
								if(args->udp_BUF == NULL)
									{
									printf("MEM ALLLOC PROBLEM\n");
									exit(0);
								}

								bzero(&args->PMU_addr,sizeof(PMU_addr));
								args->PMU_addr.sin_family=PMU_addr.sin_family;
								args->PMU_addr.sin_addr.s_addr=PMU_addr.sin_addr.s_addr;
								args->PMU_addr.sin_port=PMU_addr.sin_port;
								memset(&(args->PMU_addr.sin_zero), '\0', 8);   // zero the rest of the struct

								args->PMU_addr = PMU_addr;
								copy_cbyc(args->udp_BUF,udp_BUF,bytes_read);

								args->udp_sockfd = udp_sockfd;
								args->bytes_read = bytes_read;
							//	usleep(app1_delay);
                      			createStartTimerThreadAtDelayedArrival(args);
                      			continue;
									}

							else if(IsDelayed == 0 && id == LostPmuId) {
								drop_count++;
								continue;
							}
							else {

								int t_index = matchDataFrameTimeToTSBTime_NoUpdate(soc,fsec,id);


								//printf("Initial Match :key=%s t_index = %d soc =%lu fracsec=%lu\n",key,t_index,soc,fsec);
								if(t_index != 99 && t_index != -1) {
									//printf("First Packet Match :key=%s t_index = %d soc =%lu fracsec=%lu\n",key,t_index,soc,fsec);

									Analysing(11,id,pmusoc,pmufracsec,t_index);
								}
							}

						}
						//Analysing(11,id,pmusoc,pmufracsec,0);
						//Analysing(61,id,pmusoc,pmufracsec,0);
						/*						Analysing(20,id,pmusoc,pmufracsec); */
						//app2_Analysing(20,id,soc,fsec,pmusoc,pmufracsec);


					}
				}			


				udp_BUF[bytes_read] = '\0';
					PMU_process_UDP(udp_BUF,PMU_addr,udp_sockfd);



				} else {

					printf("Datagram PMU not authentic. We donot pass the buffer for further processing %s %d\n",inet_ntoa(their_addr.sin_addr),id);
				} 					
			} // Main if ends

		} // while ends
	}

	close(udp_sockfd);
	pthread_exit(NULL);
}
void* connect_pmu_tcp(void *temp) {

	int tcp_sockfd,port_num,yes = 1;
	struct sockaddr_in PMU_addr;
	struct Lower_Layer_Details *temp_pmu = (struct Lower_Layer_Details *) temp;
	unsigned char *tcp_BUF,*ptr,length[2];
	unsigned int flen;	
	uint16_t cal_crc,frame_crc;

	port_num = temp_pmu->port;

	if ((tcp_sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		perror("socket");
		exit(1);
	}

	if (setsockopt(tcp_sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
		perror("setsockopt");
		exit(1);
	}

	bzero(&PMU_addr,sizeof(PMU_addr));
	PMU_addr.sin_family = AF_INET;
	PMU_addr.sin_addr.s_addr =  inet_addr(temp_pmu->ip);  
	PMU_addr.sin_port = htons(port_num);
	memset(&(PMU_addr.sin_zero), '\0', 8);   // zero the rest of the struct

	/* Copy the information of Lower Layer PMU/PDC to the node */
	temp_pmu->thread_id = pthread_self();
	bzero(&temp_pmu->llpmu_addr,sizeof(PMU_addr));
	temp_pmu->llpmu_addr.sin_family = AF_INET;
	temp_pmu->llpmu_addr.sin_addr.s_addr =  inet_addr(temp_pmu->ip); 
	temp_pmu->llpmu_addr.sin_port = htons(port_num);
	memset(&(temp_pmu->llpmu_addr.sin_zero), '\0', 8);   // zero the rest of the struct
	temp_pmu->sockfd = tcp_sockfd;
	temp_pmu->up = 1;

	if (connect(tcp_sockfd, (struct sockaddr *)&PMU_addr,
			sizeof(PMU_addr)) == -1) { // Main if

		perror("connect");
		temp_pmu->up = 0;
		add_PMU_Node(temp_pmu);	
		pthread_exit(NULL);

	} else {
		/* Add PMU*/
		add_PMU_Node(temp_pmu);	

		tcp_BUF = malloc(MAXBUFLEN* sizeof(unsigned char));

		/* Sending Command for obtaining CFG */
		int n,bytes_read;
		char *cmdframe = malloc(19);
		cmdframe[18] = '\0';
		create_command_frame(1,temp_pmu->pmuid,cmdframe);
		if ((n = send (tcp_sockfd,cmdframe,18,0) == -1)) { 

			perror("send");

		} else {	

			free(cmdframe);
			while(1) {

				memset(tcp_BUF, '\0', MAXBUFLEN * sizeof(unsigned char));						
				bytes_read = recv (tcp_sockfd, tcp_BUF,MAXBUFLEN-1,0);

				if(bytes_read == 0) {  /* When  TCP Peer Terminates */

					printf("No data received Closing tcp socket %d\n",tcp_sockfd);
					temp_pmu->up = 0;

					struct Upper_Layer_Details *temp_pdc = ULfirst;
					pthread_mutex_lock(&mutex_Upper_Layer_Details);							
					while(temp_pdc != NULL ) {

						temp_pdc->config_change = 1;
						temp_pdc = temp_pdc->next;
					}
					pthread_mutex_unlock(&mutex_Upper_Layer_Details);

					pthread_exit(NULL);

				} else if(bytes_read == -1) {/* When  TCP Peer Terminates */

					perror("recv");
					temp_pmu->up = 0;

					struct Upper_Layer_Details *temp_pdc = ULfirst;
					pthread_mutex_lock(&mutex_Upper_Layer_Details);							
					while(temp_pdc != NULL ) {

						temp_pdc->config_change = 1;
						temp_pdc = temp_pdc->next;
					}
					pthread_mutex_unlock(&mutex_Upper_Layer_Details);

				} else {

					unsigned char c = tcp_BUF[1];
					c <<= 1;
					c >>= 5;
/*					if(c == 0x00)*/
/*						pthread_mutex_lock(&mutex_on_thread); // Added by KK on 19-Oct-2013*/

					char *idcode,*soC,*fracsec;
					idcode = malloc(2*sizeof(unsigned char));
					soC = malloc(4*sizeof(unsigned char));
					fracsec = malloc(3*sizeof(unsigned char));

					ptr = tcp_BUF;
					ptr+=4;
					copy_cbyc(idcode,ptr,2);
					ptr+=2;
					copy_cbyc(soC,ptr,4);
					ptr+=5;		
					copy_cbyc(fracsec,ptr,3);

					unsigned int id,soc,fsec;
					id = to_intconvertor(idcode);
					soc= to_long_int_convertor(soC);
					fsec = to_long_int_convertor1(fracsec);
					free(idcode);
					free(soC);
					free(fracsec);	
					

					if(frame_crc != cal_crc) {

						continue;		
					}
					/*if (sendto(DB_sockfd,tcp_BUF, MAXBUFLEN-1, 0,
							(struct sockaddr *)&DB_Server_addr,sizeof(DB_Server_addr)) == -1) {
						perror("sendto");
					}*/

					tcp_BUF[bytes_read] = '\0';
					PMU_process_TCP(tcp_BUF,tcp_sockfd);
				}  

			} // while ends
		} 
	}// Main if

	close(tcp_sockfd);
	pthread_exit(NULL);
}
void VoltageStability(struct data_frame *df,ENTRY *ent) { // for fixed point the phunits are not considered

//	printf("Inside VoltageStability\n");
	unsigned int lPDCID,pmuID;
	unsigned int numOfPMUs,i,pIndex;
	ENTRY entry;
	ENTRY *found=NULL;
	ENTRY *found1;
	unsigned char format;
	struct MapPMUToPhasor *tempMapPMUToPhasor;
	struct Phasor *phasor;
	
	unsigned char *fp_angle,*fx_angle,polar,*d;
	float angle,threshold;

	fp_angle = malloc(5*sizeof(unsigned char));
	fx_angle = malloc(3*sizeof(unsigned char));	

	while(df!=NULL) { // populate the hash table with actual phasor values

		lPDCID = to_intconvertor(df->idcode);
		numOfPMUs = df->num_pmu;
		for(i = 0;i<numOfPMUs;i++) {

			pmuID = df->dpmu[i]->idcode;
			memset(pmuIDKey,'\0',10);			
			sprintf(pmuIDKey,"%d",pmuID);
        	pmuKey = pmuIDKey;
			entry.key = pmuKey;						
			hsearch_r( entry,FIND, &found,&hashForMapPMUToPhasor);	
			
			if(found != NULL) {

				tempMapPMUToPhasor = ((struct MapPMUToPhasor *)found->data);
				format = tempMapPMUToPhasor->format;
				int nn = ((struct MapPMUToPhasor *)found->data)->numOfPhasors;
				int ll =0;
				while(ll<nn) {

					pIndex = ((struct MapPMUToPhasor *)found->data)->PhasorIndex[ll];
					d = df->dpmu[i]->phasors[pIndex];
					if((format & 0x20) == 0x20) { // floating

						d += 4;
						copy_cbyc (fp_angle,d,4);
						fp_angle[4] = '\0';
						angle = decode_ieee_single(fp_angle);					

					} else {

						d += 2;
						copy_cbyc (fx_angle,d,2);
						fx_angle[2] = '\0';
						angle = to_intconvertor(fx_angle);					
					}

					memset(appKey,'\0',50);					
					sprintf(appKey,"%d%d%d%s",1,lPDCID,pmuID,((struct MapPMUToPhasor *)found->data)->PhasorName[ll]);
					//printf("Key %s\n",appKey );
					key = appKey;
					entry.key = key;
					hsearch_r( entry,FIND, &found1,&hashForVSAppDetails);	
					if(found1 != NULL) {

						((struct VSAppDetails *)found1->data)->Phasor_Value = angle;
					} else {
						//printf("No key %s some problem PhasorName %s\n",appKey,((struct MapPMUToPhasor *)found->data)->PhasorName[pIndex]);
					}
					
					ll++;
				}
			}
		}
		df = df->dnext;
	} // while to populate phasor value ends
	
	// Angle difference application
	float angleDiff,angle1,angle2;
	threshold = ((struct VSAppInfo *)ent->data)->threshold;
	
	int noOfApps = ((struct VSAppInfo *)ent->data)->noOfApps;	
	//int noOfApps = 14;	
	ENTRY *found2,*found3;	
	for(i =0;i<noOfApps;i++) {

		entry.key = VSHashKeyList.key[i];
		hsearch_r(entry,FIND, &found2,&hashForVSAppDetails);	
		if(found2 != NULL)
		{
			entry.key = ((struct VSAppDetails *)found2->data)->peerHashKey;
			hsearch_r(entry,FIND, &found3,&hashForVSAppDetails);	
			angle1 = ((struct VSAppDetails *)found2->data)->Phasor_Value;
			angle2 = ((struct VSAppDetails *)found3->data)->Phasor_Value;
			if(fabs(angle1-angle2+TWOPI) > threshold){
			//	printf("violation of threshold\n");
				;
			}
		}
	}
}
Exemple #6
0
void free_cfgframe_object(struct cfg_frame *cfg) { 

	int j = 0;
	unsigned int phn,ann,dgn,num_pmu;
	struct dgnames *t_dgnames,*r_dgnames; 

	num_pmu = to_intconvertor(cfg->num_pmu);

	while(j<num_pmu) {		  					

		free(cfg->pmu[j]->stn);
		free(cfg->pmu[j]->idcode);
		free(cfg->pmu[j]->data_format);
		free(cfg->pmu[j]->fmt);

		// Extract PHNMR, DGNMR, ANNMR
		phn = to_intconvertor(cfg->pmu[j]->phnmr);
		ann = to_intconvertor(cfg->pmu[j]->annmr);
		dgn = to_intconvertor(cfg->pmu[j]->dgnmr);

		if(phn != 0)
			free_2darray(cfg->pmu[j]->cnext->phnames,phn);
		if(ann != 0)
			free_2darray(cfg->pmu[j]->cnext->angnames,ann);

		if(dgn != 0) {
			t_dgnames = cfg->pmu[j]->cnext->first;

			while(t_dgnames != NULL) {

				r_dgnames = t_dgnames->dg_next;
				free_2darray(t_dgnames->dgn,16);
				t_dgnames = r_dgnames;
			}
		}

		if(phn != 0)
			free_2darray(cfg->pmu[j]->phunit,phn);
		if(ann != 0)
			free_2darray(cfg->pmu[j]->anunit,ann);
		if(dgn != 0)
			free_2darray(cfg->pmu[j]->dgunit,dgn);

		free(cfg->pmu[j]->phnmr);
		free(cfg->pmu[j]->annmr);
		free(cfg->pmu[j]->dgnmr);
		free(cfg->pmu[j]->fnom);
		free(cfg->pmu[j]->cfg_cnt);

		j++;
	} // End of While 

	free(cfg->framesize);
	free(cfg->idcode);
	free(cfg->soc);
	free(cfg->fracsec);
	free(cfg->time_base);
	free(cfg->data_rate);
	free(cfg->num_pmu);
	free(cfg);			
}