Example #1
0
int SocketAndSendto(int bcast, int reply, const char* dest)
{
    int sockfd;
    struct addrinfo hints, *servinfo, *p;
    int retval;
    int numbytes;
    int broadcast = 1;
    char* packet;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = (bcast) ? AF_INET : AF_UNSPEC;
    hints.ai_socktype = SOCK_DGRAM;

    if ((retval = getaddrinfo(dest, "49364", &hints, &servinfo)) != 0)
    {
        printfLog("client: getaddrinfo(): %s", gai_strerror(retval));
        return 4;
    }

    for(p = servinfo; p != NULL; p = p->ai_next)
    {   // Loop through all results from getaddrinfo() and use the first one that works.
        if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1)
        {
            printLogError("client: socket()", errno);
            continue;
        }

        break;
    }

    if (p == NULL)
    {
        printLog("client: failed to create socket");
        return 5;
    }

    if(bcast)
        if(setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof broadcast) == -1)
        {
            printLogError("client: setsockopt(SO_BROADCAST)", errno);
            return 6;
        }

    packet = encapPacket(reply, hostname);
    printfLog("client: sent %s: %d bytes to %s", ((reply) ? "response" : "request"), strlen(packet), dest);
    if(packet)
    {
        if ((numbytes = sendto(sockfd, packet, strlen(packet), 0, p->ai_addr, p->ai_addrlen)) == -1)
        {
            printLogError("client: sendto()", errno);
            return 7;
        }
        free(packet);
    }

    freeaddrinfo(servinfo);

    close(sockfd);

    return 0;
}
Example #2
0
int main (int argc, char *argv [])
{
  FILE *fp;
  getRec *signalGetRec;
  file *f;
  int ii, kk, ll, mm, give_usage_action=0, offset;
  int filter_azimuth, filter_range, filter_size;
  struct ARDOP_PARAMS params;
  meta_parameters *meta;
  complexFloat *image_in, *image_out, impulse_response, sum;
  double lines=0.0, samples=0.0;
  double time, range_time, azimuth_time, beam_center_time, pulse_duration;
  double pulse_envelope, antenna_beam_pattern, wavelength, chirp_slope;
  double slant_range, pulse_repetition_frequency, range_sampling_rate;
  double exposure_time, r, theta;
  
  printf("%s\n",date_time_stamp());
  fflush(NULL);
  printf("Program: atdp\n\n");
  
  logflag=0;
  quietflag=1;
  
  give_usage_action=parse_cla(argc,argv,&params,&meta);
  if (give_usage_action==0) give_usage(argv[0]);
 
  if (logflag) {
    StartWatchLog(fLog);
    printLog("Program: atdp\n\n");
  }
  printf("   Initialization ...\n"); 

  /* Read input out of SAR processing parameter file */
  atdp_setup(&params,meta,&f,&signalGetRec);
  
  /* Define some parameters */
  beam_center_time = samples * lines / 2; // check!!!
  pulse_duration = params.pulsedur;
  wavelength = params.wavl;
  chirp_slope = params.slope;
  pulse_repetition_frequency = params.prf;
  range_sampling_rate = params.fs;
  exposure_time = 0.64; // fix me
  filter_azimuth = (int)(exposure_time * pulse_repetition_frequency / 2 + 0.5);
  filter_range = (int)(pulse_duration * range_sampling_rate / 2 + 0.5);
  filter_size = filter_azimuth * filter_range * 4;

  /* Write metadata */
  lines = signalGetRec->nLines;
  samples = signalGetRec->nSamples;
  meta->general->line_count = lines - filter_azimuth*2;
  meta->general->sample_count = samples - filter_range*2;
  meta->general->data_type = COMPLEX_REAL32;
  meta->general->image_data_type = COMPLEX_IMAGE;
  meta_write(meta, f->out_cpx);

  /* Arrange for memory */
  image_in = (complexFloat *) MALLOC (sizeof(complexFloat)*samples*lines);
  image_out = (complexFloat *) MALLOC (sizeof(complexFloat)*meta->general->sample_count);

  /* Read raw SAR image */
  for (ii=0; ii<lines; ii++)
    getSignalLine(signalGetRec,ii,&image_in[ii],0,samples);
  
  /* Open output image */
  fp = FOPEN(f->out_cpx, "wb");

  /* Loop through the image */
  printf("   Start SAR processing raw image ...\n");
  printf("   Match filter size: %i lines, %i samples\n", 
	 filter_azimuth*2, filter_range*2);
  for (ii=filter_azimuth; ii<lines-filter_azimuth; ii++) {
    for (kk=filter_range; kk<samples-filter_range; kk++) {

      offset = ii*samples + kk;
      ll=0;mm=0;

      /* Apply match filter */
      for (ll=0; ll<filter_azimuth*2; ll++) {
	for (mm=0; mm<filter_range*2; mm++) {
	  
	  sum.real = 0.0;
	  sum.imag = 0.0;
	  
	  /* Determine range and azimuth time */
	  range_time = (kk+mm) * meta->sar->range_time_per_pixel;
	  azimuth_time = (ii+ll) * meta->sar->azimuth_time_per_pixel;
	  
	  /* Envelope of transmitted radar pulse */
	  slant_range = meta_get_slant(meta, ii+ll, kk+mm);
	  time = range_time - 2*slant_range/speedOfLight;
	  pulse_envelope = rect(time, pulse_duration);
	  
	  /* Antenn beam pattern */
	  time = azimuth_time - beam_center_time;
	  antenna_beam_pattern = rect(time, pulse_duration);
	  
	  /* Impulse response function -
	     Straight out of Ian Cumming's book (4-42), written in polar coordinates.
	     For complex data, we have z = r * exp(i*theta). The real part out of that
	     is r*cos(theta), the imaginary part is r*sin(theta).*/
	  r = pulse_envelope * antenna_beam_pattern;
	  theta = (-4*PI * slant_range * wavelength) +
	    (PI * chirp_slope * SQR(range_time - 2*slant_range / speedOfLight));
	  
	  /* Real and imaginary part of impulse response function */
	  impulse_response.real = r * cos(theta);
	  impulse_response.imag = r * sin(theta);
	  
	  /* Multiplication of raw image with time reversed complex conjugate 
	     impulse response function */
	  sum.real += 
	    image_in[offset + ll*filter_range*2 + mm].real * impulse_response.real + 
	    image_in[offset + ll*filter_range*2 + mm].imag * impulse_response.imag;
	  sum.imag += 
	    image_in[offset + ll*filter_range*2 + mm].imag * impulse_response.real -
	    image_in[offset + ll*filter_range*2 + mm].real * impulse_response.imag;
	}
      }

      image_out[kk].real = sum.real / filter_size;
      image_out[kk].imag = sum.imag / filter_size; 
      //printf("   image: line = %5i, sample = %5i\r", ii, kk);

    }
    put_complexFloat_line(fp, meta, ii, image_out);
    if (ii%200 == 0) 
      printf("   Processed line %5d\n", ii);

  }
  FCLOSE(fp);
  
  return(0);
}
Example #3
0
void SerialInterface::readData(float deltaTime) {
#ifdef __APPLE__
    
    int initialSamples = totalSamples;
    
    if (USING_INVENSENSE_MPU9150) { 
        unsigned char sensorBuffer[36];
        
        // ask the invensense for raw gyro data
        write(_serialDescriptor, "RD683B0E\n", 9);
        read(_serialDescriptor, sensorBuffer, 36);
        
        int accelXRate, accelYRate, accelZRate;
        
        convertHexToInt(sensorBuffer + 6, accelZRate);
        convertHexToInt(sensorBuffer + 10, accelYRate);
        convertHexToInt(sensorBuffer + 14, accelXRate);
        
        const float LSB_TO_METERS_PER_SECOND2 = 1.f / 16384.f * GRAVITY_EARTH;
                                                                //  From MPU-9150 register map, with setting on
                                                                //  highest resolution = +/- 2G
        
        _lastAcceleration = glm::vec3(-accelXRate, -accelYRate, -accelZRate) * LSB_TO_METERS_PER_SECOND2;
                
        
        int rollRate, yawRate, pitchRate;
        
        convertHexToInt(sensorBuffer + 22, rollRate);
        convertHexToInt(sensorBuffer + 26, yawRate);
        convertHexToInt(sensorBuffer + 30, pitchRate);
        
        //  Convert the integer rates to floats
        const float LSB_TO_DEGREES_PER_SECOND = 1.f / 16.4f;     //  From MPU-9150 register map, 2000 deg/sec.
        glm::vec3 rotationRates;
        rotationRates[0] = ((float) -pitchRate) * LSB_TO_DEGREES_PER_SECOND;
        rotationRates[1] = ((float) -yawRate) * LSB_TO_DEGREES_PER_SECOND;
        rotationRates[2] = ((float) -rollRate) * LSB_TO_DEGREES_PER_SECOND;

        // update and subtract the long term average
        _averageRotationRates = (1.f - 1.f/(float)LONG_TERM_RATE_SAMPLES) * _averageRotationRates +
                1.f/(float)LONG_TERM_RATE_SAMPLES * rotationRates;
        rotationRates -= _averageRotationRates;

        // compute the angular acceleration
        glm::vec3 angularAcceleration = (deltaTime < EPSILON) ? glm::vec3() : (rotationRates - _lastRotationRates) / deltaTime;
        _lastRotationRates = rotationRates;
        
        //  Update raw rotation estimates
        glm::quat estimatedRotation = glm::quat(glm::radians(_estimatedRotation)) *
            glm::quat(glm::radians(deltaTime * _lastRotationRates));
        
        //  Update acceleration estimate: first, subtract gravity as rotated into current frame
        _estimatedAcceleration = (totalSamples < GRAVITY_SAMPLES) ? glm::vec3() :
            _lastAcceleration - glm::inverse(estimatedRotation) * _gravity;
        
        // update and subtract the long term average
        _averageAcceleration = (1.f - 1.f/(float)LONG_TERM_RATE_SAMPLES) * _averageAcceleration +
                1.f/(float)LONG_TERM_RATE_SAMPLES * _estimatedAcceleration;
        _estimatedAcceleration -= _averageAcceleration;
        
        //  Consider updating our angular velocity/acceleration to linear acceleration mapping
        if (glm::length(_estimatedAcceleration) > EPSILON &&
                (glm::length(_lastRotationRates) > EPSILON || glm::length(angularAcceleration) > EPSILON)) {
            // compute predicted linear acceleration, find error between actual and predicted
            glm::vec3 predictedAcceleration = _angularVelocityToLinearAccel * _lastRotationRates +
                _angularAccelToLinearAccel * angularAcceleration;
            glm::vec3 error = _estimatedAcceleration - predictedAcceleration;
            
            // the "error" is actually what we want: the linear acceleration minus rotational influences
            _estimatedAcceleration = error;
            
            // adjust according to error in each dimension, in proportion to input magnitudes
            for (int i = 0; i < 3; i++) {
                if (fabsf(error[i]) < EPSILON) {
                    continue;
                }
                const float LEARNING_RATE = 0.001f;
                float rateSum = fabsf(_lastRotationRates.x) + fabsf(_lastRotationRates.y) + fabsf(_lastRotationRates.z);
                if (rateSum > EPSILON) {
                    for (int j = 0; j < 3; j++) {
                        float proportion = LEARNING_RATE * fabsf(_lastRotationRates[j]) / rateSum;
                        if (proportion > EPSILON) {
                            _angularVelocityToLinearAccel[j][i] += error[i] * proportion / _lastRotationRates[j];
                        }
                    }
                }
                float accelSum = fabsf(angularAcceleration.x) + fabsf(angularAcceleration.y) + fabsf(angularAcceleration.z);
                if (accelSum > EPSILON) {
                    for (int j = 0; j < 3; j++) {
                        float proportion = LEARNING_RATE * fabsf(angularAcceleration[j]) / accelSum;
                        if (proportion > EPSILON) {
                            _angularAccelToLinearAccel[j][i] += error[i] * proportion / angularAcceleration[j];
                        }
                    }                
                }
            }
        }
        
        // rotate estimated acceleration into global rotation frame
        _estimatedAcceleration = estimatedRotation * _estimatedAcceleration;
        
        //  Update estimated position and velocity
        float const DECAY_VELOCITY = 0.975f;
        float const DECAY_POSITION = 0.975f;
        _estimatedVelocity += deltaTime * _estimatedAcceleration;
        _estimatedPosition += deltaTime * _estimatedVelocity;
        _estimatedVelocity *= DECAY_VELOCITY;
        
        //  Attempt to fuse gyro position with webcam position
        Webcam* webcam = Application::getInstance()->getWebcam();
        if (webcam->isActive()) {
            const float WEBCAM_POSITION_FUSION = 0.5f;
            _estimatedPosition = glm::mix(_estimatedPosition, webcam->getEstimatedPosition(), WEBCAM_POSITION_FUSION);
               
        } else {
            _estimatedPosition *= DECAY_POSITION;
        }
            
        //  Accumulate a set of initial baseline readings for setting gravity
        if (totalSamples == 0) {
            _gravity = _lastAcceleration;
        } 
        else {
            if (totalSamples < GRAVITY_SAMPLES) {
                _gravity = (1.f - 1.f/(float)GRAVITY_SAMPLES) * _gravity +
                1.f/(float)GRAVITY_SAMPLES * _lastAcceleration;
            } else {
                //  Use gravity reading to do sensor fusion on the pitch and roll estimation
                estimatedRotation = safeMix(estimatedRotation,
                    rotationBetween(estimatedRotation * _lastAcceleration, _gravity) * estimatedRotation,
                    1.0f / SENSOR_FUSION_SAMPLES);
                
                //  Without a compass heading, always decay estimated Yaw slightly
                const float YAW_DECAY = 0.999f;
                glm::vec3 forward = estimatedRotation * glm::vec3(0.0f, 0.0f, -1.0f);
                estimatedRotation = safeMix(glm::angleAxis(glm::degrees(atan2f(forward.x, -forward.z)),
                    glm::vec3(0.0f, 1.0f, 0.0f)) * estimatedRotation, estimatedRotation, YAW_DECAY);
            }
        }
        
        _estimatedRotation = safeEulerAngles(estimatedRotation); 
        
        totalSamples++;
    } 
    
    if (initialSamples == totalSamples) {        
        timeval now;
        gettimeofday(&now, NULL);
        
        if (diffclock(&lastGoodRead, &now) > NO_READ_MAXIMUM_MSECS) {
            printLog("No data - Shutting down SerialInterface.\n");
            resetSerial();
        }
    } else {
        gettimeofday(&lastGoodRead, NULL);
    }
#endif
}
Example #4
0
void RedoUUID(char *SQLFile) 
{
	MYSQL *conn = NULL ;
	MYSQL_RES *res_set = NULL;
	MYSQL_ROW row = NULL;
	char sqltxt[MAX_BUFF] ;
	char Buff[MAX_BUFF] ;

	int ret, cnt, j, n, len_db_ouuid, len_db_uuid;
	char db_productid[18+1];
	char db_date[19+1];
	char db_status;
	char db_uuid[50+1];
	char db_old_uuid[50+1];
	int	uuid_mode, ouuid_mode;


	FILE    *Basefp = NULL;
	int	i, Count = 0;
	//DATA_T	Data;
	int *Data;

	Count = CountLineNumber(SQLFile);

	printLog(HEAD, "Count(%d)\n", Count);
	if((Basefp = fopen(SQLFile, "rb")) == NULL)	{
		printf("File(%s) Open Error..\n", SQLFile);
		exit(-1);
	}

	if((Data = (int *) malloc(sizeof(int) * Count)) == NULL)        {
		printf("Memory Allocation Error..\n");
		exit(-1);
	}

	for(i = 0; i < Count; i++)  {
		fscanf(Basefp, "%d", &Data[i]);
//		printf("Code(%d)\n", Data[i]);
	}

	fclose(Basefp);

	Count = RemoveRedunduntUUID(Data, Count);

	printLog(HEAD, "After RemoveRedunduntUUID()...Count(%d)\n", Count);
	for(i=0; i<Count; i++) {
		printLog(HEAD, "UUID(%d)(%d/%d)\n", Data[i], i, Count);
	}

	ret = mydbc_init(&conn);
	if(ret != DB_SUCCESS) {
		printLog(HEAD, "ERR: mydbc_init[%d]\n", ret);
		exit(0);
	}

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

		//sprintf(sqltxt, "select uuid, status, productid, p_date from product_now where pda_type = 'K7' and uuid = '%d' and status = 'H'", Data[i]);
		//sprintf(sqltxt, "select uuid, status, productid, p_date from product_now where pda_type = 'K2' and uuid = '%d' and status = 'H'", Data[i]);
		//sprintf(sqltxt, "select uuid, status, productid, p_date from product_now where pda_type = 'K3' and uuid = '%d' and status = 'H'", Data[i]);
		//sprintf(sqltxt, "select uuid, status, productid, p_date from product_now where pda_type = 'K3+' and uuid = '%d' and status = 'H'", Data[i]);
		//sprintf(sqltxt, "select uuid, status, productid, p_date from product_now where pda_type = 'KE1' and uuid = '%d' and status = 'H'", Data[i]);
		sprintf(sqltxt, "select uuid, status, productid, p_date from product_now where pda_type = 'RVW' and uuid = '%d' and status = 'H'", Data[i]);
		printLog(HEAD, "%s\n", sqltxt);

		if((ret = mydbc_execute_get_result(&conn, sqltxt, &cnt, &res_set)) != DB_SUCCESS) {
			printLog(HEAD, "ERR : mydbc_execute_get_result(%d)\n", ret);
			if((ret = mydbc_end(&conn)) != DB_SUCCESS)  {
				printLog(HEAD, "ERR : mydbc_end(%d)\n", ret);
				exit(0);
			}
			exit(0);
		}

		if(cnt == 0) {
			//printLog(HEAD, "WARNNING::[%d]No Factory Auth Data... UUID(%d)\n", i, Data[i]);
			printLog(HEAD, "OK::[%d]No Previous Auth Productid... UUID(%d)\n", i, Data[i]);
		}
		else if(cnt == 1){
			for(j = 0; j < cnt; j++) {
				if((row = mydbc_next_row(&res_set)) == NULL) break;
				n = -1;

				memset(db_uuid, 0, 51);
				memset(db_productid, 0, 19);
				memset(db_date, 0, 20);

				if(row[++n] != NULL) strcpy(db_uuid, row[n]);
				if(row[++n] != NULL) db_status = row[n][0];
				if(row[++n] != NULL) strcpy(db_productid, row[n]);
				if(row[++n] != NULL) strcpy(db_date, row[n]);

				//printLog(HEAD, "WARNNING::[%d]Previous Auth Product ID[%s] exist... UUID(%d)\n", i, db_productid, Data[i]);
				printLog(HEAD, "WARNNING %s %d %s\n", db_productid, Data[i], db_date);

			}
		}
		else {
			printLog(HEAD, "WARNNING::[%d]Previous Auth Product exist count(%d)... UUID(%d)\n", i, cnt, Data[i]);
		}
		mydbc_free_result(&res_set);
	}

	ret = mydbc_end(&conn);
	if(ret != DB_SUCCESS) {
		printLog(HEAD, "ERR: mydbc_end[%d]\n", ret);
		exit(0);
	}
}
Example #5
0
void printTaskStatus(std::string pre_or_cur, int status)
{
	printLog("%s ----- %s\n",pre_or_cur.c_str(),getTaskStatusString(status).c_str());
}
Example #6
0
int	GetParamsReqSearchProductInfo(Q_ENTRY *req, REQ_SEARCH_PRODUCT_INFO_T *Query)
{
	char *Count;
	char *Mode;
	char *UserProductIDList;
	int	i = 0, j = 0, idx = 0;
	char	temp[MIN_BUFF_SIZE+1];

	if((Count = (char *) req->getStr(req, "Count", false)) != NULL)	{
		Query->Count = atoi(Count); 
		if(Query->Count < 1)	{
			printLog(HEAD, "ClientIP(%s)::Count(%d) Error\n", getenv("REMOTE_ADDR"), Query->Count);
			return	ERR_INVALID_PARAM;
		}
	}
	else	
	{
		printLog(HEAD, "ClientIP(%s)::Count Err\n", getenv("REMOTE_ADDR"));
		return	ERR_INVALID_PARAM;
	}

	if((Mode = (char *) req->getStr(req, "Mode", false)) != NULL)   {
		Query->Mode = Mode[0];
		if(Query->Mode != 'I' && Query->Mode != 'T')
			Query->Mode = 'I';
	}
	else
	{
		Query->Mode = 'I';
	}

	if((UserProductIDList = (char *) req->getStr(req, "UserProductIDList", false)) != NULL)	{
		if((Query->SearchKey = (USER_PRODUCTID_T *) malloc(sizeof(USER_PRODUCTID_T) * Query->Count)) == NULL)	{
			printLog(HEAD, "HERE:Count(%d)MemoryAlloc\n", Query->Count);
			return	ERR_INVALID_PARAM;
		}
		idx = 0;
		memset(Query->SearchKey, 0, sizeof(USER_PRODUCTID_T) * Query->Count);
		for(i = 0; i < Query->Count; i++)	{
			memset(temp, 0, MIN_BUFF_SIZE+1);
			for(j = 0; UserProductIDList[idx] != '|' && UserProductIDList[idx] != '\0'; idx++, j++)	{
				temp[j] = UserProductIDList[idx];
			}
			memcpy(Query->SearchKey[i].UserID, temp, USERID_SIZE);
			idx++;

			memset(temp, 0, MIN_BUFF_SIZE+1);
			for(j = 0; UserProductIDList[idx] != '|' && UserProductIDList[idx] != '\0'; idx++, j++)	{
				temp[j] = UserProductIDList[idx];
			}
			memcpy(Query->SearchKey[i].ProductID, temp, PRODUCTID_SIZE);
			idx++;
		}
	}
	else	
	{
		printLog(HEAD, "ClientIP(%s)::UserProductIDList Err\n", getenv("REMOTE_ADDR"));
		return	ERR_INVALID_PARAM;
	}

	printLog(HEAD, "<<<****** Search Product Info Input::ClientIP(%s)::Count(%d)\n", getenv("REMOTE_ADDR"), Query->Count);
	for(i = 0; i < Query->Count; i++)	{
		printLog(HEAD, "\(%d) UserID(%.20s) ProductID(%.18s)\n", (i+1), Query->SearchKey[i].UserID, Query->SearchKey[i].ProductID);
	}
	printLog(HEAD, "******>>>\n");

	return	NO_ERROR;
}
Example #7
0
RES_SEARCH_PRODUCT_INFO_T *ProcessSearchProductInfo(REQ_SEARCH_PRODUCT_INFO_T InQuery, int *ResultCount, int *ErrorCode)
{
	int	SocketFD;
	int	len = 0, idx = 0, i = 0;
	int	Count = 0;
	struct timeval tmv;
	fd_set readset;

	char	MsgID;
	char	ret_stat;
	char	*SendBuff;
	int	ReadSize = 0;
	char	ReadBuff[MIN_BUFF_SIZE+1];
	RES_SEARCH_PRODUCT_INFO_T *Data;

	ReadSize = USERID_SIZE + PRODUCTID_SIZE + 3 + TIMESTAMP_SIZE + VERSION_SIZE + SOFTWAREVERSION_SIZE
		+ MAPDATA_SIZE + MAPINFO_SIZE + DEVICE_SIZE + VERSION_SIZE + APPVERSION_SIZE
		+ BUILDNUM_SIZE + MAPVERSION_SIZE + OSVERSION_SIZE + FILESIZE_SIZE + EXPIREDATE_SIZE;

	if((SendBuff = (char *) malloc((USERID_SIZE+PRODUCTID_SIZE) * InQuery.Count + MIN_BUFF_SIZE)) == NULL)	{
		printLog(HEAD, "Memory Allocation Error..\n");
		*ErrorCode = MALLOCATION_ERROR;
		*ResultCount = 0;
		return	(RES_SEARCH_PRODUCT_INFO_T *) NULL;
	}
	memset(SendBuff, 0, (USERID_SIZE+PRODUCTID_SIZE) * InQuery.Count + MIN_BUFF_SIZE);

	MsgID = MSG_SEARCH_PRODUCT_INFO;
	memcpy(SendBuff+idx, &MsgID, sizeof(MsgID));
	idx += sizeof(MsgID);

	InQuery.Count = htonl(InQuery.Count);
	memcpy(SendBuff+idx, &InQuery.Count, sizeof(InQuery.Count));
	idx += sizeof(InQuery.Count);
	InQuery.Count = ntohl(InQuery.Count);

	for(i = 0; i < InQuery.Count; i++)	{
		memcpy(SendBuff+idx, InQuery.SearchKey[i].UserID, USERID_SIZE);
		idx += USERID_SIZE;
		memcpy(SendBuff+idx, InQuery.SearchKey[i].ProductID, PRODUCTID_SIZE);
		idx += PRODUCTID_SIZE;
	}

	if((SocketFD = connect_to_server(SERVER_IP, SERVER_PORT)) < 0)	{
		printLog(HEAD, "Socket Connection Error.....\n");
		*ErrorCode = SOCKET_WRITE_ERROR;
		*ResultCount = 0;
		free(SendBuff);
		return	(RES_SEARCH_PRODUCT_INFO_T *) NULL;
	}

	if((len = writen(SocketFD, SendBuff, idx)) != idx)	{
		printLog(HEAD, "Write Error...\n");
		*ErrorCode = SOCKET_WRITE_ERROR;
		*ResultCount = 0;
		free(SendBuff);
		return	(RES_SEARCH_PRODUCT_INFO_T *) NULL;
	}

	//	free Send Buffer...
	free(SendBuff);

	tmv.tv_sec = READ_TIMEOUT;
	tmv.tv_usec = 0;

	FD_ZERO(&readset);
	FD_SET(SocketFD, &readset);

	if (select(SocketFD+1, &readset, NULL, NULL, &tmv) < 0) {
		printLog(HEAD, "select error\n");
		*ErrorCode = SOCKET_READ_ERROR;
		*ResultCount = 0;
		close(SocketFD);
		return	(RES_SEARCH_PRODUCT_INFO_T *) NULL;
	}
	if (!FD_ISSET(SocketFD, &readset)) {
		printLog(HEAD, "%d sec time out\n", READ_TIMEOUT);
		*ErrorCode = READ_TIMEOUT_ERROR;
		*ResultCount = 0;
		close(SocketFD);
		return	(RES_SEARCH_PRODUCT_INFO_T *) NULL;
	}

	if((len = readn(SocketFD, &MsgID, sizeof(MsgID))) != sizeof(MsgID))	{
		printLog(HEAD, "Read Error...\n");
		*ErrorCode = SOCKET_READ_ERROR;
		*ResultCount = 0;
		close(SocketFD);
		return	(RES_SEARCH_PRODUCT_INFO_T *) NULL;
	}

	if(MsgID == MSG_FAIL)	{
		if((len = readn(SocketFD, &ret_stat, sizeof(ret_stat))) != sizeof(ret_stat))	{
			printLog(HEAD, "Read Error...\n");
			*ErrorCode = SOCKET_READ_ERROR;
			*ResultCount = 0;
			close(SocketFD);
			return	(RES_SEARCH_PRODUCT_INFO_T *) NULL;
		}
		*ErrorCode = ret_stat;
	}
	else	{
		if((len = readn(SocketFD, &Count, sizeof(int))) != sizeof(int))	{
			printLog(HEAD, "Read Error...\n");
			*ErrorCode = SOCKET_READ_ERROR;
			*ResultCount = 0;
			close(SocketFD);
			return	(RES_SEARCH_PRODUCT_INFO_T *) NULL;
		}
		Count = ntohl(Count);
		*ResultCount = Count;
		if((Data = (RES_SEARCH_PRODUCT_INFO_T *) malloc(sizeof(RES_SEARCH_PRODUCT_INFO_T) * Count)) == NULL)	{
			printLog(HEAD, "Memory Allocation Error..\n");
			*ErrorCode = MALLOCATION_ERROR;
			*ResultCount = 0;
			return	(RES_SEARCH_PRODUCT_INFO_T *) NULL;
		}
		memset(Data, 0, sizeof(RES_SEARCH_PRODUCT_INFO_T) * Count);

		for(i = 0; i < Count; i++)	{
			idx = 0;
			memset(ReadBuff, 0, MIN_BUFF_SIZE+1);
			if((len = readn(SocketFD, ReadBuff, ReadSize)) != (ReadSize))	{
				printLog(HEAD, "Read Error...\n");
				*ErrorCode = SOCKET_READ_ERROR;
				*ResultCount = 0;
				free(Data);
				close(SocketFD);
				return	(RES_SEARCH_PRODUCT_INFO_T *) NULL;
			}
			Data[i].Exist = ReadBuff[idx];
			idx++;
			memcpy(Data[i].UserID, ReadBuff+idx, USERID_SIZE);
			idx += USERID_SIZE;
			memcpy(Data[i].ProductID, ReadBuff+idx, PRODUCTID_SIZE);
			idx += PRODUCTID_SIZE;
			Data[i].LastUse = ReadBuff[idx];
			idx++;
			Data[i].Status = ReadBuff[idx];
			idx++;
			memcpy(Data[i].TimeStamp, ReadBuff+idx, TIMESTAMP_SIZE);
			idx += TIMESTAMP_SIZE;
			memcpy(Data[i].Version, ReadBuff+idx, VERSION_SIZE);
			idx += VERSION_SIZE;
			memcpy(Data[i].SoftwareVersion, ReadBuff+idx, VERSION_SIZE);
			idx += VERSION_SIZE;
			memcpy(Data[i].MapData, ReadBuff+idx, MAPDATA_SIZE);
			idx += MAPDATA_SIZE;
			memcpy(Data[i].MapInfo, ReadBuff+idx, MAPINFO_SIZE);
			idx += MAPINFO_SIZE;
			memcpy(Data[i].DeviceType, ReadBuff+idx, DEVICE_SIZE);
			idx += DEVICE_SIZE;
			memcpy(Data[i].RegisterVersion, ReadBuff+idx, VERSION_SIZE);
			idx += VERSION_SIZE;
			memcpy(Data[i].AppVersion, ReadBuff+idx, APPVERSION_SIZE);
			idx += APPVERSION_SIZE;
			memcpy(Data[i].AppBuildNum, ReadBuff+idx, BUILDNUM_SIZE);
			idx += BUILDNUM_SIZE;
			memcpy(Data[i].MapVersion, ReadBuff+idx, MAPVERSION_SIZE);
			idx += MAPVERSION_SIZE;
			memcpy(Data[i].OSVersion, ReadBuff+idx, OSVERSION_SIZE);
			idx += OSVERSION_SIZE;
			memcpy(Data[i].FileFolderSize, ReadBuff+idx, FILESIZE_SIZE);
			idx += FILESIZE_SIZE;
			memcpy(Data[i].ExpireDate, ReadBuff+idx, EXPIREDATE_SIZE);
			idx += EXPIREDATE_SIZE;
		}
	}

	*ResultCount = Count;
	close(SocketFD);

	return	Data;
}
Example #8
0
int	main(int argc, char **argv)
{
	char	AgencyID[B2B_AGENCYID_SIZE+1];
	char	Mode;
	B2B_STATINFO_T 	*Data = NULL;
	CONFIG_T	Config;
	int	FetchedCount = 0;
	char	LogPath[256];
	double start_time=0, end_time=0;
	double real_time = 0;
	struct timeval tp_start;
	struct timeval tp_end;
	int	ErrorCode = NO_ERROR;

	Q_ENTRY *req = qCgiRequestParse(NULL, (Q_CGI_T) 0);

	gettimeofday(&tp_start, 0);

	//	Set Random Value
	srand(tp_start.tv_usec);

	memset(AgencyID, 0, B2B_AGENCYID_SIZE+1);

	ReadConfig(CONFIGFILE_PATH, &Config);

	sprintf(LogPath, "%s/%s", Config.LOG_PATH, LOG_NAME_SEARCHPRODUCTSTAT);
	SvcLog = openLog("SearchProductStatInfo", LogPath,  LOG_MODE);
	sprintf(LogPath, "%s/%s", Config.LOG_PATH, LOG_NAME_SEARCHPRODUCTSTAT_DEB);
	Log = openLog("SearchProductStatInfo", LogPath,  LOG_MODE);
	sprintf(LogPath, "%s/%s", Config.LOG_PATH, LOG_NAME_STATISTICS);
	StatLog = openLog("SearchProductStatInfo", LogPath,  LOG_MODE);

	if((ErrorCode = Connect2DB(Config)) == NO_ERROR)	{
		if((ErrorCode = GetParamsReqStatInfo(req, AgencyID, &Mode)) == NO_ERROR)	{
			if((Data = DB_SelectProductStatInfo(AgencyID, &FetchedCount, &ErrorCode)) != NO_ERROR)	{
				printLog(HEAD, "Search Error...ErrorCode(%d)\n", ErrorCode);
			}
		}
		else	{
			printLog(HEAD, "Invalid Paramters Error...(%d)\n", ErrorCode);
		}
	}
	else	{
		printLog(HEAD, "DBConnection Error...(%d)\n", ErrorCode);
	}

	if(Mode == 'T')	{
		qCgiResponseSetContentType(req, "text/html");
		PrintResultProductStatInfoWithTable(ErrorCode, AgencyID, Data, FetchedCount);
	}
	else	{
		qCgiResponseSetContentType(req, "application/json;charset=euc-kr");
		PrintResultProductStatInfo(ErrorCode, AgencyID, Data, FetchedCount);
	}

	if(Data != NULL)	
		free(Data);

	DisConnectDB();

	gettimeofday(&tp_end, 0);
	start_time = (double)tp_start.tv_sec + (double)tp_start.tv_usec/1000000;
	end_time = (double)tp_end.tv_sec + (double)tp_end.tv_usec/1000000;
	real_time = end_time - start_time;

	printLog(STAT_HEAD, "SEARCH_PRODUCT_S %d %4.6f\n", ErrorCode, real_time);
	printLog(HEAD, "---------------------------------------------------------------\n");

	closeLog(SvcLog);
	closeLog(Log);
	closeLog(StatLog);

	return	0;
}
Example #9
0
int mem_load_db_minja_link_list()
{
	int result = RES_SUCCESS;
	int ret;
	int i;

	char sql[SQL_SIZE];
	int cnt = 0;

   	MYSQL *conn = NULL;
   	MYSQL_RES *res_set = NULL;
   	MYSQL_ROW row = NULL;

	if((ret = mydbc_init(&conn)) != DB_SUCCESS) {
		printLog(Log, STAMP, "ERR: mydbc_init[%d]\n", ret);
		return RES_ERR_MYSQL_DB_CONNECT;
	}

   	memset(sql, 0x00, SQL_SIZE);    
   	sprintf(sql, "SELECT fw_linkid FROM TBL_MINJA_LINK_SPEED");

	ret = mydbc_execute_get_result(&conn, sql, &cnt, &res_set);
	if(ret != DB_SUCCESS) {
		printLog(Log, STAMP, "ERR: mydbc_execute_get_result[%d]\n", ret);
		result = RES_ERR_MYSQL_DB_BAD_SQL;
		goto Return;
	}
	printLog(Log, STAMP, "sql[%s]count[%d]\n", sql, cnt);

	if(cnt > 0) {
    	memset(&gSSPL, 0x00, sizeof(SectionSpeedList));
    	gSSPL.count = cnt;
    	gSSPL.pList = (SectionSpeed *)calloc(cnt, sizeof(SectionSpeed));

    	if(gSSPL.pList == NULL) {
        	printLog(Log, STAMP, "Fail to allocate Memory\n");
        	result = RES_ERR_MEMORY_ALLOC;
			goto Return;
    	}

		for(i = 0; i < cnt; i++) {
			row = mydbc_next_row(&res_set);

			if (row[0] != NULL) strncpy(gSSPL.pList[i].link_id, row[0], LINK_ID_SIZE);

			if(i % 10 == 0) {
				printLog(Log, STAMP, "idx[%d]LinkID[%s]\n", i, gSSPL.pList[i].link_id); 
			}
		}	

		mydbc_free_result(&res_set);

	}else {
		if(cnt == 0) {
			result = RES_ERR_MYSQL_DB_ZERO_ROW; 
		}else {
			result = RES_ERR_ETC; 
		}
		printLog(Log, STAMP, "failed mem_load_db_minja_link_list[ret:%d]\n", result); 

		return result;
	}
		
	printLog(Log, STAMP, "successed mem_load_db_minja_link_list\n"); 

Return :
	ret = mydbc_end(&conn);
	if (ret != DB_SUCCESS) {
		printLog(Log, STAMP, "ERR: mydbc_end[%d]\n", ret);
	}
	
	return result;
}
Example #10
0
File: Audio.cpp Project: tschw/hifi
inline void Audio::performIO(int16_t* inputLeft, int16_t* outputLeft, int16_t* outputRight) {

    NodeList* nodeList = NodeList::getInstance();
    Application* interface = Application::getInstance();
    Avatar* interfaceAvatar = interface->getAvatar();
 
    // Add Procedural effects to input samples
    addProceduralSounds(inputLeft, BUFFER_LENGTH_SAMPLES_PER_CHANNEL);
    
    if (nodeList && inputLeft) {
        
        //  Measure the loudness of the signal from the microphone and store in audio object
        float loudness = 0;
        for (int i = 0; i < BUFFER_LENGTH_SAMPLES_PER_CHANNEL; i++) {
            loudness += abs(inputLeft[i]);
        }
        
        loudness /= BUFFER_LENGTH_SAMPLES_PER_CHANNEL;
        _lastInputLoudness = loudness;
        
        // add input (@microphone) data to the scope
        _scope->addSamples(0, inputLeft, BUFFER_LENGTH_SAMPLES_PER_CHANNEL);

        Node* audioMixer = nodeList->soloNodeOfType(NODE_TYPE_AUDIO_MIXER);
        
        if (audioMixer) {
            glm::vec3 headPosition = interfaceAvatar->getHeadJointPosition();
            glm::quat headOrientation = interfaceAvatar->getHead().getOrientation();
            
            int numBytesPacketHeader = numBytesForPacketHeader((unsigned char*) &PACKET_TYPE_MICROPHONE_AUDIO_NO_ECHO);
            int leadingBytes = numBytesPacketHeader + sizeof(headPosition) + sizeof(headOrientation);
            
            // we need the amount of bytes in the buffer + 1 for type
            // + 12 for 3 floats for position + float for bearing + 1 attenuation byte
            unsigned char dataPacket[BUFFER_LENGTH_BYTES_PER_CHANNEL + leadingBytes];
            
            PACKET_TYPE packetType = (Application::getInstance()->shouldEchoAudio())
                ? PACKET_TYPE_MICROPHONE_AUDIO_WITH_ECHO
                : PACKET_TYPE_MICROPHONE_AUDIO_NO_ECHO;
            
            unsigned char* currentPacketPtr = dataPacket + populateTypeAndVersion(dataPacket, packetType);
            
            // memcpy the three float positions
            memcpy(currentPacketPtr, &headPosition, sizeof(headPosition));
            currentPacketPtr += (sizeof(headPosition));
            
            // memcpy our orientation
            memcpy(currentPacketPtr, &headOrientation, sizeof(headOrientation));
            currentPacketPtr += sizeof(headOrientation);
            
            // copy the audio data to the last BUFFER_LENGTH_BYTES bytes of the data packet
            memcpy(currentPacketPtr, inputLeft, BUFFER_LENGTH_BYTES_PER_CHANNEL);
            nodeList->getNodeSocket()->send(audioMixer->getActiveSocket(),
                                              dataPacket,
                                              BUFFER_LENGTH_BYTES_PER_CHANNEL + leadingBytes);

            interface->getBandwidthMeter()->outputStream(BandwidthMeter::AUDIO)
                    .updateValue(BUFFER_LENGTH_BYTES_PER_CHANNEL + leadingBytes);
        }
        
    }
    
    memset(outputLeft, 0, PACKET_LENGTH_BYTES_PER_CHANNEL);
    memset(outputRight, 0, PACKET_LENGTH_BYTES_PER_CHANNEL);
    
    AudioRingBuffer* ringBuffer = &_ringBuffer;
    
    // if there is anything in the ring buffer, decide what to do:
    
    if (ringBuffer->getEndOfLastWrite()) {
        if (!ringBuffer->isStarted() && ringBuffer->diffLastWriteNextOutput() <
            (PACKET_LENGTH_SAMPLES + _jitterBufferSamples * (ringBuffer->isStereo() ? 2 : 1))) {
            //
            //  If not enough audio has arrived to start playback, keep waiting
            //
#ifdef SHOW_AUDIO_DEBUG
            printLog("%i,%i,%i,%i\n",
                     _packetsReceivedThisPlayback,
                     ringBuffer->diffLastWriteNextOutput(),
                     PACKET_LENGTH_SAMPLES,
                     _jitterBufferSamples);
#endif
        } else if (ringBuffer->isStarted() && ringBuffer->diffLastWriteNextOutput() == 0) {
            //
            //  If we have started and now have run out of audio to send to the audio device, 
            //  this means we've starved and should restart.  
            //  
            ringBuffer->setStarted(false);
            
            _numStarves++;
            _packetsReceivedThisPlayback = 0;
            _wasStarved = 10;          //   Frames for which to render the indication that the system was starved.
#ifdef SHOW_AUDIO_DEBUG
            printLog("Starved, remaining samples = %d\n",
                     ringBuffer->diffLastWriteNextOutput());
#endif

        } else {
            //
            //  We are either already playing back, or we have enough audio to start playing back.
            // 
            if (!ringBuffer->isStarted()) {
                ringBuffer->setStarted(true);
#ifdef SHOW_AUDIO_DEBUG
                printLog("starting playback %0.1f msecs delayed, jitter = %d, pkts recvd: %d \n",
                         (usecTimestampNow() - usecTimestamp(&_firstPacketReceivedTime))/1000.0,
                         _jitterBufferSamples,
                         _packetsReceivedThisPlayback);
#endif
            }

            //
            // play whatever we have in the audio buffer
            //
            // if we haven't fired off the flange effect, check if we should
            // TODO: lastMeasuredHeadYaw is now relative to body - check if this still works.
            
            int lastYawMeasured = fabsf(interfaceAvatar->getHeadYawRate());
            
            if (!_samplesLeftForFlange && lastYawMeasured > MIN_FLANGE_EFFECT_THRESHOLD) {
                // we should flange for one second
                if ((_lastYawMeasuredMaximum = std::max(_lastYawMeasuredMaximum, lastYawMeasured)) != lastYawMeasured) {
                    _lastYawMeasuredMaximum = std::min(_lastYawMeasuredMaximum, MIN_FLANGE_EFFECT_THRESHOLD);
                    
                    _samplesLeftForFlange = SAMPLE_RATE;
                    
                    _flangeIntensity = MIN_FLANGE_INTENSITY +
                        ((_lastYawMeasuredMaximum - MIN_FLANGE_EFFECT_THRESHOLD) /
                         (float)(MAX_FLANGE_EFFECT_THRESHOLD - MIN_FLANGE_EFFECT_THRESHOLD)) *
                        (1 - MIN_FLANGE_INTENSITY);
                    
                    _flangeRate = FLANGE_BASE_RATE * _flangeIntensity;
                    _flangeWeight = MAX_FLANGE_SAMPLE_WEIGHT * _flangeIntensity;
                }
            }
            
            for (int s = 0; s < PACKET_LENGTH_SAMPLES_PER_CHANNEL; s++) {
                
                int leftSample = ringBuffer->getNextOutput()[s];
                int rightSample = ringBuffer->getNextOutput()[s + PACKET_LENGTH_SAMPLES_PER_CHANNEL];
                
                if (_samplesLeftForFlange > 0) {
                    float exponent = (SAMPLE_RATE - _samplesLeftForFlange - (SAMPLE_RATE / _flangeRate)) /
                        (SAMPLE_RATE / _flangeRate);
                    int sampleFlangeDelay = (SAMPLE_RATE / (1000 * _flangeIntensity)) * powf(2, exponent);
                    
                    if (_samplesLeftForFlange != SAMPLE_RATE || s >= (SAMPLE_RATE / 2000)) {
                        // we have a delayed sample to add to this sample
                        
                        int16_t *flangeFrame = ringBuffer->getNextOutput();
                        int flangeIndex = s - sampleFlangeDelay;
                        
                        if (flangeIndex < 0) {
                            // we need to grab the flange sample from earlier in the buffer
                            flangeFrame = ringBuffer->getNextOutput() != ringBuffer->getBuffer()
                            ? ringBuffer->getNextOutput() - PACKET_LENGTH_SAMPLES
                            : ringBuffer->getNextOutput() + RING_BUFFER_LENGTH_SAMPLES - PACKET_LENGTH_SAMPLES;
                            
                            flangeIndex = PACKET_LENGTH_SAMPLES_PER_CHANNEL + (s - sampleFlangeDelay);
                        }
                        
                        int16_t leftFlangeSample = flangeFrame[flangeIndex];
                        int16_t rightFlangeSample = flangeFrame[flangeIndex + PACKET_LENGTH_SAMPLES_PER_CHANNEL];
                        
                        leftSample = (1 - _flangeWeight) * leftSample + (_flangeWeight * leftFlangeSample);
                        rightSample = (1 - _flangeWeight) * rightSample + (_flangeWeight * rightFlangeSample);
                        
                        _samplesLeftForFlange--;
                        
                        if (_samplesLeftForFlange == 0) {
                            _lastYawMeasuredMaximum = 0;
                        }
                    }
                }
#ifndef TEST_AUDIO_LOOPBACK
                outputLeft[s] = leftSample;
                outputRight[s] = rightSample;
#else 
                outputLeft[s] = inputLeft[s];
                outputRight[s] = inputLeft[s];                    
#endif
            }
            ringBuffer->setNextOutput(ringBuffer->getNextOutput() + PACKET_LENGTH_SAMPLES);
            
            if (ringBuffer->getNextOutput() == ringBuffer->getBuffer() + RING_BUFFER_LENGTH_SAMPLES) {
                ringBuffer->setNextOutput(ringBuffer->getBuffer());
            }
        }
    }

    eventuallySendRecvPing(inputLeft, outputLeft, outputRight);


    // add output (@speakers) data just written to the scope
    _scope->addSamples(1, outputLeft, BUFFER_LENGTH_SAMPLES_PER_CHANNEL);
    _scope->addSamples(2, outputRight, BUFFER_LENGTH_SAMPLES_PER_CHANNEL);

    gettimeofday(&_lastCallbackTime, NULL);
}
Example #11
0
void process_cmd(char *readbuf, int length) {
   typedef enum pipe_cmd_type{ca,im,tl,px,bo,tv,an,as,at,ac,ab,sh,co,br,sa,is,vs,rl,ec,em,wb,mm,ie,ce,ro,fl,ri,ss,qu,pv,bi,ru,md,sc,rs,bu,mn,mt,mi,mb,me,mx,mf,vm,vp,wd,sy,cn,st} pipe_cmd_type;
   char pipe_cmds[] = "ca,im,tl,px,bo,tv,an,as,at,ac,ab,sh,co,br,sa,is,vs,rl,ec,em,wb,mm,ie,ce,ro,fl,ri,ss,qu,pv,bi,ru,md,sc,rs,bu,mn,mt,mi,mb,me,mx,mf,vm,vp,wd,sy,cn,st";
   pipe_cmd_type pipe_cmd;
   int parcount;
   char pars[128][10];
   long int par0;
   char cmd[3];
   char par[MAX_COMMAND_LEN];
   char *parstring=0, *temp;
   int key = -1;
   
   if (length < 2 || length > (MAX_COMMAND_LEN - 2)) return;
   
   //Get cmd
   strncpy(cmd, readbuf, 2);
    //find 2 letter command and translate into enum
   temp = strstr(pipe_cmds, cmd);
   if (temp == NULL) return;
   pipe_cmd = (pipe_cmd_type)((temp - pipe_cmds) / 3);
  
   if(length > 3) {
      strcpy(par, readbuf + 3);
      par[length-3] = 0;
      //extract space separated numeric parameters
      // and make separate string parameter (strtok changes the original)
      asprintf(&parstring, "%s", par);
      parcount = 0;
      temp = strtok(par, " ");
      while(parcount<10 && temp != NULL) {
         strcpy(pars[parcount], temp);
         parcount++;
         temp = strtok(NULL, " ");
      }
      par0 = strtol(pars[0], NULL, 10);
   } else {
      par0 = 0;
   }
   
   switch(pipe_cmd) {
      case ca:
         if(par0 == 1) {
            if (parcount > 1) {
               long vtime = strtol(pars[1], NULL, 10);
               video_stoptime = time(NULL) + vtime;
               printLog("Capturing %d seconds\n", vtime);
            }
            start_video(0);
         }  else {
            stop_video(0);
         }
         break;
      case im:
         capt_img();
         break;
      case tl:
         if(par0) {
            timelapse = 1;
            lapse_cnt = 1;
            updateStatus();
            printLog("Timelapse started\n");
         }
         else {
            image2_cnt++;
            timelapse = 0;
            updateStatus();
            printLog("Timelapse stopped\n");
         }
         break;
      case px:
         stop_all();
         addUserValue(c_video_width, pars[0]);
         addUserValue(c_video_height, pars[1]);
         addUserValue(c_video_fps, pars[2]);
         addUserValue(c_MP4Box_fps, pars[3]);
         addUserValue(c_image_width, pars[4]);
         addUserValue(c_image_height, pars[5]);
         start_all(0);
         break;
      case bo:
         addUserValue(c_MP4Box, pars[0]);
         break;
      case tv:
         addUserValue(c_tl_interval, pars[0]);
         break;
      case an:
         addUserValue(c_annotation, parstring);
         break;
      case as:
         addUserValue(c_anno_text_size, pars[0]);
         break;
      case at:
         addUserValue(c_anno3_custom_text_colour, pars[0]);
         addUserValue(c_anno3_custom_text_Y, pars[1]);
         addUserValue(c_anno3_custom_text_U, pars[2]);
         addUserValue(c_anno3_custom_text_V, pars[3]);
         break;
      case ac:
         addUserValue(c_anno3_custom_background_colour, pars[0]);
         addUserValue(c_anno3_custom_background_Y, pars[1]);
         addUserValue(c_anno3_custom_background_U, pars[2]);
         addUserValue(c_anno3_custom_background_V, pars[3]);
         break;
      case ab:
         addUserValue(c_anno_background, pars[0]);
         break;
      case sh:
         key = c_sharpness;
         break;
      case co:
         key = c_contrast;
         break;
      case br:
         key = c_brightness;
         break;
      case sa:
         key = c_saturation;
         break;
      case is:
         key = c_iso;
         break;
      case vs:
         key = c_video_stabilisation;
         break;
      case rl:
         key = c_raw_layer;
         break;
      case ec:
         key = 1000 + c_exposure_compensation;
         break;
      case em:
         key = 1000 + c_exposure_mode;
         break;
      case wb:
         key = 1000 + c_white_balance;
         break;
      case mm:
         key = 1000 + c_metering_mode;
         break;
      case ie:
         key = 1000 + c_image_effect;
         break;
      case ce:
         addUserValue(c_colour_effect_u, pars[1]);
         addUserValue(c_colour_effect_v, pars[2]);
         key = c_colour_effect_en;
         break;
      case ro:
         key = c_rotation;
         break;
      case fl:
         if(par0 & 1) addUserValue(c_hflip, "1"); else addUserValue(c_hflip, "0"); 
         if((par0 >> 1) & 1) addUserValue(c_vflip, "1"); else addUserValue(c_vflip, "0"); 
         cam_set(c_hflip);
         break;
      case ri:
         addUserValue(c_sensor_region_y, pars[1]);
         addUserValue(c_sensor_region_w, pars[2]);
         addUserValue(c_sensor_region_h, pars[3]);
         key = c_sensor_region_x;
         break;
      case ss:
         addUserValue(c_shutter_speed, pars[0]);
         key = c_shutter_speed;
         break;
      case qu:
         key = c_image_quality;
         break;
      case pv:
         stop_all();
         addUserValue(c_quality, pars[0]);
         addUserValue(c_width, pars[1]);
         addUserValue(c_divider, pars[2]);
         start_all(0);
         break;
      case bi:
         stop_all();
         addUserValue(c_video_bitrate, pars[0]);
         start_all(0);
         break;
      case st:
         stop_all();
         addUserValue(c_stat_pass, pars[0]);
         start_all(0);
         break;
      case wd:
         addUserValue(c_watchdog_interval, pars[0]);
         addUserValue(c_watchdog_errors, pars[1]);
         break;
      case ru:
         if (par0 == 0) {
            stop_all();
            idle = 1;
            printLog("Stream halted\n");
         } else {
            start_all(1);
            idle = 0;
            printLog("Stream continued\n");
         }
         updateStatus();
         break;
      case mx:
         key = c_motion_external;
         //If switching to internal with motion detection on then try to kill external motion
         if (cfg_val[c_motion_detection] != 0 && !par0) {
            if(system("killall motion") == -1) error("Could not stop external motion", 1);
            printLog("External motion detection stopped\n");
         }
         break;
      case md:
         exec_macro(cfg_stru[c_do_cmd], readbuf);
         stop_all();
         if (cfg_val[c_motion_external]) {
            if(par0 == 0) {
               if(system("killall motion") == -1) error("Could not stop external motion", 1);
               printLog("External motion detection stopped\n");
            }
            else {
               if (cfg_val[c_motion_detection] == 0) {
                  if(system("motion") == -1) error("Could not start external motion", 1);
                  printLog("External motion detection started\n");
               } else {
                  printLog("Motion already running. md 1 ignored\n");
               }
            }
         } else {
            if(par0 == 0) {
               printLog("Internal motion detection stopped\n");
            }
            else {
               printLog("Internal motion detection started\n");
            }
         }
         cfg_val[c_motion_detection] = par0?1:0;
         start_all(0);
         updateStatus();
         break;
      case sc:
         set_counts();
         printLog("Scan for highest count\n");
         break;
      case rs:
         printLog("Reset settings to defaults\n");
         stop_all();
         read_config("/etc/raspimjpeg", 1);
         saveUserConfig(cfg_stru[c_user_config]);
         start_all(0);
         break;
      case bu:
         key = c_video_buffer;
         break;
      case vp:
         stop_all();
         addUserValue(c_vector_preview, pars[0]);
         start_all(0);
         break;
      case mn:
         key = c_motion_noise;
         break;
      case mt:
         key = c_motion_threshold;
         break;
      case mi:
         key = c_motion_image + 1000;
         break;
      case mb:
         key = c_motion_startframes;
         break;
      case me:
         key = c_motion_stopframes;
         break;
      case mf:
         key = c_motion_file;
         break;
      case vm:
         key = c_vector_mode;
         break;
      case sy:
         exec_macro(parstring, NULL);
         break;
      case cn:
         stop_all();
         addUserValue(c_camera_num, pars[0]);
         start_all(0);
         break;
      default:
         printLog("Unrecognised pipe command\n");
         break;
   }
Example #12
0
File: Audio.cpp Project: tschw/hifi
inline void Audio::analyzePing() {

    // Determine extrema
    int botAt = findExtremum(_echoSamplesLeft, PING_SAMPLES_TO_ANALYZE, -1);
    if (botAt == -1) {
        printLog("Audio Ping: Minimum not found.\n");
        return;
    }
    int topAt = findExtremum(_echoSamplesLeft, PING_SAMPLES_TO_ANALYZE, 1);
    if (topAt == -1) {
        printLog("Audio Ping: Maximum not found.\n");
        return;
    }

    // Determine peak amplitude - warn if low
    int ampli = (_echoSamplesLeft[topAt] - _echoSamplesLeft[botAt]) / 2;
    if (ampli < PING_MIN_AMPLI) {
        printLog("Audio Ping unreliable - low amplitude %d.\n", ampli);
    }

    // Determine period - warn if doesn't look like our signal
    int halfPeriod = abs(topAt - botAt);
    if (abs(halfPeriod-PING_HALF_PERIOD) > PING_MAX_PERIOD_DIFFERENCE) {
        printLog("Audio Ping unreliable - peak distance %d vs. %d\n", halfPeriod, PING_HALF_PERIOD);
    }

    // Ping is sent:
    //
    // ---[ record ]--[  play  ]--- audio in space/time --->
    //    :        :           :
    //    :        : ping: ->X<-
    //    :        :         :
    //    :        :         |+| (buffer end - signal center = t1-t0)
    //    :      |<----------+
    //    :      : :         :
    //    :    ->X<- (corresponding input buffer position t0)
    //    :      : :         :
    //    :      : :         :
    //    :      : :         :
    // Next frame (we're recording from now on):
    //    :      : :
    //    : -  - --[ record ]--[  play  ]------------------>
    //    :      : :         :
    //    :      : |<-- (start of recording t1)
    //    :      : :
    //    :      : :
    // At some frame, the signal is picked up:
    //    :      : :         :
    //    :      : :         : 
    //    :      : :         V
    //    :      : : -  - --[ record ]--[  play  ]---------->
    //    :      V :         :
    //    :      |<--------->|
    //           |+|<------->|  period + measured samples
    //
    // If we could pick up the signal at t0 we'd have zero round trip
    // time - in this case we had recorded the output buffer instantly
    // in its entirety (we can't - but there's the proper reference
    // point). We know the number of samples from t1 and, knowing that
    // data is streaming continuously, we know that t1-t0 is the distance
    // of the characterisic point from the end of the buffer.

    int delay = (botAt + topAt) / 2 + PING_PERIOD;

    printLog("\n| Audio Ping results:\n+----- ---- --- - -  -   -   -\n\n"
             "Delay = %d samples (%d ms)\nPeak amplitude = %d\n\n",
             delay, (delay * 1000) / int(SAMPLE_RATE), ampli);
}
Example #13
0
File: Audio.cpp Project: tschw/hifi
Audio::Audio(Oscilloscope* scope, int16_t initialJitterBufferSamples) :
    _stream(NULL),
    _ringBuffer(true),
    _scope(scope),
    _averagedLatency(0.0),
    _measuredJitter(0),
    _jitterBufferSamples(initialJitterBufferSamples),
    _wasStarved(0),
    _numStarves(0),
    _lastInputLoudness(0),
    _lastVelocity(0),
    _lastAcceleration(0),
    _totalPacketsReceived(0),
    _firstPacketReceivedTime(),
    _echoSamplesLeft(NULL),
    _packetsReceivedThisPlayback(0),
    _isSendingEchoPing(false),
    _pingAnalysisPending(false),
    _pingFramesToRecord(0),
    _samplesLeftForFlange(0),
    _lastYawMeasuredMaximum(0),
    _flangeIntensity(0.0f),
    _flangeRate(0.0f),
    _flangeWeight(0.0f)
{
    outputPortAudioError(Pa_Initialize());
    
    //  NOTE:  Portaudio documentation is unclear as to whether it is safe to specify the
    //         number of frames per buffer explicitly versus setting this value to zero.
    //         Possible source of latency that we need to investigate further.
    // 
    unsigned long FRAMES_PER_BUFFER = BUFFER_LENGTH_SAMPLES_PER_CHANNEL;
    
    //  Manually initialize the portaudio stream to ask for minimum latency
    PaStreamParameters inputParameters, outputParameters;
    
    inputParameters.device = Pa_GetDefaultInputDevice();
    outputParameters.device = Pa_GetDefaultOutputDevice();

    if (inputParameters.device == -1 || outputParameters.device == -1) {
        printLog("Audio: Missing device.\n");
        outputPortAudioError(Pa_Terminate());
        return;
    }

    inputParameters.channelCount = 2;                    //  Stereo input
    inputParameters.sampleFormat = (paInt16 | paNonInterleaved);
    inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultLowInputLatency;
    inputParameters.hostApiSpecificStreamInfo = NULL;

    outputParameters.channelCount = 2;                    //  Stereo output
    outputParameters.sampleFormat = (paInt16 | paNonInterleaved);
    outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputParameters.device)->defaultLowOutputLatency;
    outputParameters.hostApiSpecificStreamInfo = NULL;
    
    outputPortAudioError(Pa_OpenStream(&_stream, 
                                       &inputParameters,
                                       &outputParameters,
                                       SAMPLE_RATE,
                                       FRAMES_PER_BUFFER,
                                       paNoFlag,
                                       audioCallback,
                                       (void*) this));
        
    if (! _stream) {
        return;
    }
 
    _echoSamplesLeft = new int16_t[AEC_BUFFERED_SAMPLES + AEC_TMP_BUFFER_SIZE];
    memset(_echoSamplesLeft, 0, AEC_BUFFERED_SAMPLES * sizeof(int16_t));
    
    // start the stream now that sources are good to go
    outputPortAudioError(Pa_StartStream(_stream));
    
    // Uncomment these lines to see the system-reported latency
    //printLog("Default low input, output latency (secs): %0.4f, %0.4f\n",
    //         Pa_GetDeviceInfo(Pa_GetDefaultInputDevice())->defaultLowInputLatency,
    //         Pa_GetDeviceInfo(Pa_GetDefaultOutputDevice())->defaultLowOutputLatency);
    
    const PaStreamInfo* streamInfo = Pa_GetStreamInfo(_stream);
    printLog("Started audio with reported latency msecs In/Out: %.0f, %.0f\n", streamInfo->inputLatency * 1000.f,
             streamInfo->outputLatency * 1000.f);

    gettimeofday(&_lastReceiveTime, NULL);
}
Example #14
0
File: Audio.cpp Project: tschw/hifi
static void outputPortAudioError(PaError error) {
    if (error != paNoError) {
        printLog("-- portaudio termination error --\n");
        printLog("PortAudio error (%d): %s\n", error, Pa_GetErrorText(error));
    }
}
Example #15
0
int main(int argc,char* argv[])
{
	if(argc!=3)
	{
		usage(argv[0]);
		return 1;
	}
	char* ip=argv[1];
	int port=atoi(argv[2]);
	int listen_sock=startup(ip,port);
	struct sockaddr_in client;
	socklen_t len=sizeof(client);
	int epo_fd=epoll_create(256);
	if(epo_fd<0)//success:not 0 fd/error:-1
	{
		printLog(strerror(errno),__FUNCTION__,__LINE__);
		return -1;
	}
	bf_p fd_bf=(bf_p)malloc(sizeof(bf_t));
	memset(fd_bf->_buf,'\0',sizeof(fd_bf->_buf));
	fd_bf->_fd=listen_sock;
	struct epoll_event ev;
	ev.events=EPOLLIN;
	ev.data.fd=listen_sock;
	if(epoll_ctl(epo_fd,EPOLL_CTL_ADD,listen_sock,&ev)<0)//success:0 fail:-1
	{
		printLog(strerror(errno),__FUNCTION__,__LINE__);
		return -1;
	}
	struct epoll_event evfds[_SIZE_];//_SIZE_ 1024
	int _timeout=5000;
	int ret=-1;
	
	int i=0;
	while(1)
	{
		switch((ret=epoll_wait(epo_fd,evfds,_SIZE_,_timeout)))
		{
			case -1://error
				printLog(strerror(errno),__FUNCTION__,__LINE__);
				break;
			case 0://time out
				printf("time out...\n");
				break;
			default://normal
				{
					for(i=0;i<ret;++i)
					{
						if(evfds[i].data.fd==listen_sock&&evfds[i].events&EPOLLIN)
						{
							int new_sock=accept(listen_sock,(struct sockaddr*)&client,&len);
							if(new_sock<0)
							{
								printLog(strerror(errno),__FUNCTION__,__LINE__);
								continue;
							}
							bf_p _bf=(bf_p)malloc(sizeof( bf_t));
							memset(_bf->_buf,'\0',sizeof(_bf->_buf));
							_bf->_fd=new_sock;

							ev.events=EPOLLIN;
							ev.data.ptr=_bf;
							epoll_ctl(epo_fd,EPOLL_CTL_ADD,new_sock,&ev);
						}
						else if(((bf_p)(evfds[i].data.ptr))->_fd>0&&evfds[i].events&EPOLLIN)
						{
							accept_request(evfds[i].data.ptr);
							ev.events=EPOLLOUT;
							ev.data.ptr=evfds[i].data.ptr;
							epoll_ctl(epo_fd,EPOLL_CTL_MOD,((bf_p)(evfds[i].data.ptr))->_fd,&ev);
						}
						else if(((bf_p)(evfds[i].data.ptr))->_fd>0&&evfds[i].events&EPOLLOUT)
						{
							bf_p _bf=(bf_p)evfds[i].data.ptr;
							if(_bf->_err)
							{
								send(_bf->_fd,_bf->_buf,strlen(_bf->_buf),0);
							}
							else if(_bf->_cgi)//cgi=1
							{
								send(_bf->_fd,_bf->_buf,strlen(_bf->_buf),0);
							}
							else
							{
								char* path=_bf->_path;
								int fd=open(path,O_RDONLY);
								if(fd<0)
								{
									printLog(strerror(errno),__FUNCTION__,__LINE__);
									exit(1);
								}
								send(_bf->_fd,_bf->_buf,strlen(_bf->_buf),0);
								if(sendfile(_bf->_fd,fd,NULL,_bf->_st_size)<0)
								{
									printf("error");
								}
								close(fd);
							}
		
							epoll_ctl(epo_fd,EPOLL_CTL_DEL,_bf->_fd,NULL);
							close(_bf->_fd);
							free(_bf);
						}
					}

					break;
				}
		}
	}
	return 0;
}
Example #16
0
int main(int argc, char **argv)
{
    if (argc != 3 && argc != 4)
    {
        std::cout << "Usage: Maxit_tester <program1> <program2> [<seed>]\n";
        return 1;
    }
    const char *program1 = argv[1];
    const char *program2 = argv[2];

    // init field
    if (argc >= 4)
        srand(atoi(argv[3]));
    else
        srand((unsigned int)time(NULL));
    for (int i = 0 ; i < size ; ++i)
    {
        for (int j = 0 ; j < size ; ++j)
        {
            field[i][j] = rand() % size + 1;
        }
    }
    col = 1;
    row = 1;

    // save field and score before the first move
    saveField(1);

    bool first = true;
    ExecutionResult result = ER_OK;
    for (int move = 0 ; move < size * size ; ++move)
    {
        std::ostringstream outs;
        for (int i = 0 ; i < size ; ++i)
        {
            for (int j = 0 ; j < size ; ++j)
            {
                outs << field[i][j] << " ";
            }
            outs << "\n";
        }
		outs << !first + 1 << "\n" << (first ? row : col) << "\n"; 
        std::string output;
        printInput(first, outs.str());
        result = runProcess(first ? program1 : program2, 
            outs.str(), output, 1000, 64000);
        if (result == ER_OK)
        {
            InStream ins(output);

            int rowcol;
            try
            {
                ins >> ValueInBounds<int>(rowcol, 1, size);
            }
            catch (ReadCheckerException &exception)
            {
                result = ER_IM;

                std::ostringstream outs;
                outs << output << std::endl << exception.getReadResultText() << ": " << exception.what() << std::endl;

                printLog(first, result, outs.str());
                break;
            }

            if  (
                    (first && field[row-1][rowcol-1]) ||
                    (!first && field[rowcol-1][col-1])
                )
            {

                if (first)
                    col = rowcol;
                else
                    row = rowcol;

                printLog(first, result, output);

                scores[!first] += field[row-1][col-1];
                
                field[row-1][col-1] = -field[row-1][col-1];
                // save field and score after the correct move
                saveField(!first + 1);
                field[row-1][col-1] = 0;

                // get next player
                bool canFirst = checkFirst(row);
                bool canSecond = checkSecond(col);
                if ((first && canSecond)
                    || (!first && canFirst))
                    first = !first;
                else if (canFirst)
                    first = true;
                else if (canSecond)
                    first = false;
                else 
                    break;
            }
            else
            {
                result = ER_IM;
                printLog(first, result, output);
                break;
            }
        }
        else
        {
Example #17
0
int sub_t_login(T_REQUEST_H *t_hd, T_RESULT_H *t_rd, int c_size, char *cookies)
{
	int error = E_NO_ERR ;
	int sockfd ;
	int wlen, rlen ;
	struct sockaddr_in serv_addr;

	I_REQUEST_H hd;
	I_RESULT_H rd;

	memset(&hd, 0, sizeof(I_REQUEST_H)) ;
	memset(&rd, 0, sizeof(I_RESULT_H)) ;

	hd.serviceid = htonl(t_hd->serviceid);
	hd.version = htonl(t_hd->eng_version);
	hd.size = htonl(c_size);

	memset((char *) &serv_addr, 0, sizeof(serv_addr)) ;
	serv_addr.sin_family = AF_INET ;
	serv_addr.sin_addr.s_addr = inet_addr(Config.T_USER_IP) ;
	serv_addr.sin_port = htons(Config.T_USER_PORT) ;

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		printLog(HEAD, "ERR: (%d) (%s)(%d)clientsoc: can't open stream socket\n", 
			t_hd->mdn, Config.T_USER_IP, Config.T_USER_PORT) ;
		error = E_TCP_SUB_USER ;
		goto error_exit ;
	}

	if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
		printLog(HEAD, "ERR: (%d) (%s)(%d)clientsoc: can't connect to server\n", 
			t_hd->mdn, Config.T_USER_IP, Config.T_USER_PORT) ;
		error = E_TCP_SUB_USER ;
		goto error_exit ;
	}

	///[SEND]///////////////////////////
	if((wlen = writen(sockfd, &hd, sizeof(I_REQUEST_H))) != sizeof(I_REQUEST_H)) {
		printLog(HEAD, "ERR: (%d) (%s)(%d)write I_REQUEST_H[wlen:%d]\n", 
			t_hd->mdn, Config.T_USER_IP, Config.T_USER_PORT, wlen) ;
		error = E_TCP_SUB_USER ;
		goto error_exit ;
	}
	printLog(HEAD, "SEND: (%d) I_REQUEST_H[wlen:%d]\n", t_hd->mdn, wlen) ;

	if((wlen = writen(sockfd, cookies, c_size)) != c_size) {
		printLog(HEAD, "ERR: (%d) (%s)(%d)write I_LOGIN_IN[wlen:%d]\n", 
			t_hd->mdn, Config.T_USER_IP, Config.T_USER_PORT, wlen) ;
		error = E_TCP_SUB_USER ;
		goto error_exit ;
	}
	printLog(HEAD, "SEND: (%d) I_LOGIN_IN[wlen:%d]\n", t_hd->mdn, wlen) ;

	///[READ]///////////////////////////
	if ((rlen = readn(sockfd, &rd, sizeof(I_RESULT_H))) != sizeof(I_RESULT_H)) {
		printLog(HEAD, "ERR: (%d) (%s)(%d)read I_RESULT_H[rlen:%d]\n", 
			t_hd->mdn, Config.T_USER_IP, Config.T_USER_PORT, rlen) ;
		error = E_TCP_SUB_USER ;
		goto error_exit ;
	}
	printLog(HEAD, "READ: (%d) I_RESULT_H[rlen:%d]\n", t_hd->mdn, rlen) ;

	rd.error = ntohl(rd.error) ;
	rd.serviceid = ntohl(rd.serviceid) ;
	rd.version = ntohl(rd.version) ;
	printLog(HEAD, "(%d) I_RESULT_H: error[%d] serviceid[%d] ver[%d]\n", t_hd->mdn, rd.error, rd.serviceid, rd.version) ;

error_exit :
	if(error != E_TCP_SUB_USER) t_rd->error = rd.error;
	else t_rd->error = error;

	close(sockfd);

	return error;
}
Example #18
0
//provide the value
CPar::CPar(complex<double> v)
{
    new CPar();
    setValue(v);
    if(debug) printLog("CPar\t", value, "\n");
}
Example #19
0
int	PrintResultSearchProductInfoWithTable(int Count, int ErrorCode, RES_SEARCH_PRODUCT_INFO_T *Data)
{
	int	i = 0;

	printLog(HEAD, "ErrorCode(%d)\n", ErrorCode);

	printf("<table cellspacing=0 width=\"200\" border = \"1\" bordercolor=black>\n");
	printf("<tr align=center>\n");
		printf("<td width=\"50\"> Result </td>\n");
		printf("<td width=\"50\"> %d </td>\n", ErrorCode);
		printf("<td width=\"50\"> Count </td>\n");
		printf("<td width=\"50\"> %d </td>\n", Count);
	printf("</tr>\n");
	printf("</table>\n");

	printf("<table cellspacing=1 width=\"500\" border = \"1\" bordercolor=black>\n");
	printf("<tr align=center>\n");
		printf("<th width=\"50\" bgcolor=\"yellow\">¼ø¹ø</td>\n");
		printf("<th width=\"150\" bgcolor=\"yellow\">ProductID</td>\n");
		printf("<th width=\"150\" bgcolor=\"yellow\">UserID</td>\n");
		printf("<th width=\"150\" bgcolor=\"yellow\">LastUse</td>\n");
		printf("<th width=\"150\" bgcolor=\"yellow\">Status</td>\n");
		printf("<th width=\"150\" bgcolor=\"yellow\">TimeStamp</td>\n");
		printf("<th width=\"150\" bgcolor=\"yellow\">Version</td>\n");
		printf("<th width=\"150\" bgcolor=\"yellow\">SoftwareVersion</td>\n");
		printf("<th width=\"150\" bgcolor=\"yellow\">MapData</td>\n");
		printf("<th width=\"150\" bgcolor=\"yellow\">MapInfo</td>\n");
		printf("<th width=\"150\" bgcolor=\"yellow\">DeviceType</td>\n");
		printf("<th width=\"150\" bgcolor=\"yellow\">RegisterVersion</td>\n");
		printf("<th width=\"150\" bgcolor=\"yellow\">AppVersion</td>\n");
		printf("<th width=\"150\" bgcolor=\"yellow\">AppBuildVersion</td>\n");
		printf("<th width=\"150\" bgcolor=\"yellow\">MapVersion</td>\n");
		printf("<th width=\"150\" bgcolor=\"yellow\">OSVersion</td>\n");
		printf("<th width=\"150\" bgcolor=\"yellow\">FileFolderSize</td>\n");
		printf("<th width=\"150\" bgcolor=\"yellow\">ExpireDate</td>\n");
		printf("<th width=\"150\" bgcolor=\"yellow\">Exist</td>\n");
	printf("</tr>\n");

	for(i = 0; i < Count; i++)  {
		printf("<tr align=center>\n");
			printf("<td width=\"50\">%d</td>\n", i+1);
			printf("<td width=\"150\"><font face=\"±¼¸²Ã¼\">%s</font></td>\n", Data[i].ProductID);
			printf("<td width=\"150\">%s</font></td>\n", Data[i].UserID);
			printf("<td width=\"150\">%c</font></td>\n", Data[i].LastUse);
			printf("<td width=\"150\">%c</font></td>\n", Data[i].Status);
			printf("<td width=\"150\">%s</font></td>\n", Data[i].TimeStamp);
			printf("<td width=\"150\">%s</font></td>\n", Data[i].Version);
			printf("<td width=\"150\">%s</font></td>\n", Data[i].SoftwareVersion);
			printf("<td width=\"150\">%s</font></td>\n", Data[i].MapData);
			printf("<td width=\"150\">%s</font></td>\n", Data[i].MapInfo);
			printf("<td width=\"150\">%s</font></td>\n", Data[i].DeviceType);
			printf("<td width=\"150\">%s</font></td>\n", Data[i].RegisterVersion);
			printf("<td width=\"150\">%s</font></td>\n", Data[i].AppVersion);
			printf("<td width=\"150\">%s</font></td>\n", Data[i].AppBuildNum);
			printf("<td width=\"150\">%s</font></td>\n", Data[i].MapVersion);
			printf("<td width=\"150\">%s</font></td>\n", Data[i].OSVersion);
			printf("<td width=\"150\">%s</font></td>\n", Data[i].FileFolderSize);
			printf("<td width=\"150\">%s</font></td>\n", Data[i].ExpireDate);
			printf("<td width=\"150\">%c</font></td>\n", Data[i].Exist);
		printf("</tr>\n");

	}

	printf("</table>\n");

	fflush(stdout);

	return	NO_ERROR;
}
Example #20
0
RES_COUPON_INFO_T	*ProcessSearchCoupon(REQ_COUPONID_T Query, int *Count, int *ErrorCode)
{
	int	SocketFD;
	int	i, len;
	struct timeval tmv;
	fd_set readset;

	REQ_HEADER_T	InputHeader;
	RES_HEADER_T	OutputHeader;
	RES_COUPON_INFO_T 	*Data;

	memset(&InputHeader, 0, sizeof(REQ_HEADER_T));
	memset(&OutputHeader, 0, sizeof(RES_HEADER_T));

	InputHeader.Version = VERSION_01;
	InputHeader.ServiceID = MSG_SEARCHBYCOUPON_REQ;

	if((SocketFD = connect_to_server(SERVER_IP, SERVER_PORT)) < 0)	{
		printLog(HEAD, "Socket Connection Error.....\n");
		*ErrorCode = SOCKET_CONNECT_ERROR;
		*Count = 0;
		return	(RES_COUPON_INFO_T *) NULL;
	}

	InputHeader.Version = htonl(InputHeader.Version);
	InputHeader.ServiceID = htonl(InputHeader.ServiceID);

	if((len = writen(SocketFD, &InputHeader, sizeof(REQ_HEADER_T))) != sizeof(REQ_HEADER_T))	{
		printLog(HEAD, "Write Error...\n");
		*ErrorCode = SOCKET_WRITE_ERROR;
		*Count = 0;
		return	(RES_COUPON_INFO_T *) NULL;
	}
	if((len = writen(SocketFD, &Query, sizeof(REQ_COUPONID_T))) != sizeof(REQ_COUPONID_T))	{
		printLog(HEAD, "Write Error...\n");
		*ErrorCode = SOCKET_WRITE_ERROR;
		*Count = 0;
		return	(RES_COUPON_INFO_T *) NULL;
	}
	tmv.tv_sec = READ_TIMEOUT;
	tmv.tv_usec = 0;

	FD_ZERO(&readset);
	FD_SET(SocketFD, &readset);

	if (select(SocketFD+1, &readset, NULL, NULL, &tmv) < 0) {
		printLog(HEAD, "select error\n");
		*ErrorCode = SOCKET_READ_ERROR;
		*Count = 0;
		close(SocketFD);
		return  (RES_COUPON_INFO_T *) NULL;
	}
	if (!FD_ISSET(SocketFD, &readset)) {
		printLog(HEAD, "%d sec time out\n", READ_TIMEOUT);
		*ErrorCode = READ_TIMEOUT_ERROR;
		*Count = 0;
		close(SocketFD);
		return  (RES_COUPON_INFO_T *) NULL;
	}

	if((len = readn(SocketFD, &OutputHeader, sizeof(RES_HEADER_T))) != sizeof(RES_HEADER_T))	{
		printLog(HEAD, "Read Error...\n");
		*ErrorCode = SOCKET_READ_ERROR;
		*Count = 0;
		close(SocketFD);
		return	(RES_COUPON_INFO_T *) NULL;
	}

	OutputHeader.Version = ntohl(OutputHeader.Version);
	OutputHeader.ServiceID = ntohl(OutputHeader.ServiceID);
	OutputHeader.ErrorCode = ntohl(OutputHeader.ErrorCode);
	OutputHeader.Count = ntohl(OutputHeader.Count);

	printLog(HEAD, "Version(%d)ServiceID(%d)ErrorCode(%d)Count(%d)\n",
			OutputHeader.Version, OutputHeader.ServiceID, OutputHeader.ErrorCode, OutputHeader.Count);

	*ErrorCode = OutputHeader.ErrorCode;
	*Count = OutputHeader.Count;

	if(OutputHeader.ErrorCode != NO_ERROR)	{
		printLog(HEAD, "Error...Code(%d)\n", OutputHeader.ErrorCode);
		*ErrorCode = OutputHeader.ErrorCode;
		*Count = OutputHeader.Count;
		close(SocketFD);
		return	(RES_COUPON_INFO_T *) NULL;
	}
	else	{
		if((Data = (RES_COUPON_INFO_T *) malloc(sizeof(RES_COUPON_INFO_T) * OutputHeader.Count)) == NULL)	{
			printLog(HEAD, "Memory Allocation Error...count(%d)\n", OutputHeader.Count);
			*ErrorCode = OutputHeader.ErrorCode;
			*Count = OutputHeader.Count;
			close(SocketFD);
			return	(RES_COUPON_INFO_T *) NULL;
		}	
		memset(Data, 0, sizeof(RES_COUPON_INFO_T) * OutputHeader.Count);
		for(i = 0; i < OutputHeader.Count; i++)	{
			if((len = readn(SocketFD, &Data[i], sizeof(RES_COUPON_INFO_T))) != sizeof(RES_COUPON_INFO_T))	{
				printLog(HEAD, "Read Error...\n");
				*ErrorCode = SOCKET_READ_ERROR;
				*Count = 0;
				free(Data);
				close(SocketFD);
				return	(RES_COUPON_INFO_T *) NULL;
			}

			printLog(HEAD, "(%d)::CouponID(%.16s)YYMM(%.4s)CID(%.4s)Serial(%.6s)CD(%.8s)RD(%.8s)ED(%.8s)DD(%.8s)MC(%.8s)EM(%.2s)DM(%.2s)Stat(%.2s)TS(%.20s)PID(%.20s)\n", i, Data[i].CouponID, Data[i].YYMM, Data[i].ChannelID, Data[i].Serial, Data[i].CreateDate, Data[i].RegistDate, Data[i].ExpireDate, Data[i].DueDate, Data[i].MemberCode, Data[i].ExpireMonth, Data[i].DueMonth, Data[i].Status, Data[i].LastUpdateTimeStamp, Data[i].ProductID);
		}
	}
	close(SocketFD);

	return	Data;
}
Example #21
0
int	main(int argc, char *argv[])
{
	pid_t	pid;
	char	config_file_path[CFG_FILE_LEN+1];
	char	CurrentDate[DATE_SIZE+1];
	int	ret;
	int	DBStatus;

	memset(CurrentDate, 0, DATE_SIZE+1);
	//	int	i;
#ifdef	__DEBUG_LOG
	//	int	j;
#endif
	//	char	FileName[CFG_FILE_LEN];

	if((pid = fork()) < 0)
		return  -1;
	else    if(pid != 0)
		exit(0);

	set_signal();

	if (argc == 5) {
		if(strcmp("-f", argv[1]) ==0)	{
			strcpy(config_file_path, argv[2]);
		}
		else	{
			printf("---------------------------------\n");
			printf("-%s -f ConfigFilePath UserID DeviceType \n", argv[0]);
			printf("---------------------------------\n");
		}
	}
	else	{
		printf("---------------------------------\n");
		printf("-%s -f ConfigFilePath UserID DeviceType \n", argv[0]);
		printf("---------------------------------\n");
	}

	printf("config(%s)\n", config_file_path);

	if(ReadConfig(config_file_path, &Config) < 0)	{
		printf("Configuration File Read Error\n");
		exit(1);
	}

	printf("log(%s)\n", Config.SERVICE_LOG_PATH);
	SvcLog = openLog("PozUTIL", Config.SERVICE_LOG_PATH, LOG_MODE);

	//  REM이 미 구동시에는 어떻게 할겨????
	//  일단 무조건 Wait하다로 코딩
	while(GetCurrentDBStatus(Config.REMIP, Config.REMPort, &DBStatus) != NO_ERROR)  {
		printLog(HEAD, "REM return ERROR... So retry to Connect REM..\n");
		printLog(HEAD, "DBStatus change to ONDBWORK_STATUS\n");
		sleep(1);
	}
		
    printLog(HEAD, ">>>>REM Reports DB Status is (%d)..<<<<\n", DBStatus);
	if(DBStatus != NORMAL_STATUS)   {
		while(DBStatus == ONDBWORK_STATUS)  {
			sleep(REM_RECONNECTION_SLEEP);
			GetCurrentDBStatus(Config.REMIP, Config.REMPort, &DBStatus);
			printLog(HEAD, "REM return ERROR... So retry to Connect REM..\n");
		}
		if(DBStatus == EXCEPTION_STATUS)    {
			char    DB_HOST_temp[CFG_FILE_LEN];

			printLog(HEAD, "So Change DB Configurations..DB_HOST(%s)<=>(%s)DB_HOST_BACKUP\n", Config.DB_HOST, Config.DB_HOST_BACKUP);

			sprintf(DB_HOST_temp, "%s", Config.DB_HOST);
			sprintf(Config.DB_HOST, "%s", Config.DB_HOST_BACKUP);
			sprintf(Config.DB_HOST_BACKUP, "%s", DB_HOST_temp);

			printLog(HEAD, "Configuration temporaly Changed...DB_HOST(%s)<=>(%s)DB_HOST_BACKUP\n", Config.DB_HOST, Config.DB_HOST_BACKUP);
		}
	}

	printConfigLog(&Config);

	printLog(HEAD, "------------------Init Service---------------\n");
	if((ret = mydbc_connect(Config.DB_NAME, Config.DB_USER, Config.DB_PASSWORD, Config.DB_HOST, Config.DB_PORT, Config.DB_CONN_COUNT)) != DB_SUCCESS)	{
		printLog(HEAD, "DB Connection ERROR[%d]\n", ret);
		exit(0);
	}
	else	{
		printLog(HEAD, "DB Connection Success...\n");
	}

	//	Conncurrent Connection Count를 구하기 위함....
	pthread_mutex_init(&p_lock, NULL);
	pthread_mutex_init(&serial_lock, NULL);
	thread_count = 0;

	//	OnCenter와 연동하는 Thread로 분기
	BatchProcess(argv[3], argv[4]);

	return	NO_ERROR;
}
Example #22
0
/*
 * readConfigFile(): read configuration from file, skipping auctions
 *
 * returns:
 *	0 file successfully read, even if no configuration options found
 *	1 file not found
 *	2 other error
 */
int
readConfigFile(const char *filename, optionTable_t *table)
{
	char *buf = NULL;
	size_t bufsize = 0, count = 0;
	int c, ret = 0;
	FILE *fp = fopen(filename, "r");

	if (fp == NULL) {
		/* file not found is OK */
		if (errno == ENOENT)
			return 1;
		printLog(stderr, "Cannot open %s: %s\n", filename,
			 strerror(errno));
		return 2;
	}

	while ((c = getc(fp)) != EOF) {
		if (isspace(c))
			continue;
		/* skip comments and anything starting with a number,
		 * assuming this is an auction entry */
		if ((c == '#') || isdigit(c))
			c = skipline(fp);
		else if (isalpha(c)) {
			char *name = NULL, *value = NULL;

			count = 0;
			do {
				addchar(buf, bufsize, count, (char)c);
				c = getc(fp);
			} while (c != EOF && !isspace(c) && c != '=');
			addchar(buf, bufsize, count, '\0');
			name = buf;

			if (c != EOF && c != '\n' && c != '\r') {
				do {
					c = getc(fp);
				} while (c == ' ' || c == '\t');
				if (c == '=') {
					do {
						c = getc(fp);
					} while (c == ' ' || c == '\t');
				}

				if (c != EOF && c != '\n' && c != '\r') {
					value = &buf[count];
					do {
						addchar(buf, bufsize, count, (char)c);
						c = getc(fp);
					} while (c != EOF && c != '\n' && c != '\r');
					/* strip trailing whitespace */
					while (isspace((int)(buf[count - 1])))
						--count;
					term(buf, bufsize, count);
				}
			}
			if (parseConfigValue(name, value, table, filename, buf))
				ret = 2;
		}

		/* don't read EOF twice! */
		if (c == EOF)
			break;
	}

	if (ferror(fp)) {
		printLog(stderr, "Cannot read %s: %s\n", filename,
			 strerror(errno));
		ret = 2;
	}
	fclose(fp);
	free(buf);
	return ret;
} /* readConfigFile() */