// ISrsBufferReader
int SimpleSocketStream::read(void* buf, size_t size, ssize_t* nread,int nConnect)
{
    int ret = ERROR_SUCCESS;
	nConnect = 1;
	if(nConnect == 0)
	{
		*nread = ::recv(m_ffffd, (char*)buf, size, 0);
	}
 	else
 	{
//        int a = JVGetTime();
//         printf("tcp_receive spendtime begin\n");
 		*nread = tcp_receive(m_ffffd, (char*)buf, size, 3);
//        int b  = JVGetTime();
//        printf("tcp_receive spendtime end : %d\n",(b-a));
		if(*nread == 0)
		{
			*nread = 0;
			//recv_bytes += *nread;
			
			return -999;
		}
		if(*nread == -1)//断开
		{
			*nread = -1;
			//recv_bytes += *nread;
			
			return -9999;
		}
	} 
    // On success a non-negative integer indicating the number of bytes actually read is returned
    // (a value of 0 means the network connection is closed or end of file is reached).
    if (*nread <= 0)
	{
  /*      if (errno == ETIME)
		{
            return ERROR_SOCKET_TIMEOUT;
        }

        if (*nread == 0)
		{
            errno = ECONNRESET;
        }
        */
        return ERROR_SOCKET_READ;
    }

    recv_bytes += *nread;

    return ret;
}
Beispiel #2
0
long tcp_getdata (TCPSTREAM *stream)
{
  char tmp[MAILTMPLEN];
  int i,status;
  /* Note: the doc says we need here dynamic descriptor, but we need static
   * one... */
  struct dsc$descriptor BufDesc = {BUFLEN,DSC$K_DTYPE_T,DSC$K_CLASS_S,
				     stream->ibuf};
  static short iosb[4];
  if (stream->tcpsi < 0) return NIL;
  while (stream->ictr < 1) {	/* if nothing in the buffer */
    if (!((status = tcp_receive(&(stream->tcpsi), &BufDesc, iosb)) & 0x1)) {
      sprintf (tmp,"Error reading from TcpIp/NETLIB, status=%d",status);
      mm_log (tmp,ERROR);
      return tcp_abort (stream);
    }
    if (iosb[1] > BUFLEN) i = BUFLEN;
    else i = iosb[1];
    if (i < 1) return tcp_abort (stream);
    stream->ictr = i;		/* set new byte count */
    stream->iptr = stream->ibuf;/* point at TCP buffer */
  }
  return T;
}
Beispiel #3
0
void query()
{
	fd_set fdsetr, fdsetw;
	struct timeval timeout;
	int min;
	struct queries *q;
	int i, n;
	struct addrinfo hints, *res0;
	int error;

	Queries = Xmalloc(sizeof(Queries[0]) * nQueries);
	memset(&remote, 0, sizeof(remote));
	memset(&hints, 0, sizeof(hints));
	hints.ai_family = family;
	hints.ai_socktype = SOCK_STREAM;
	printf("resolving: %s:%s\n", ServerName, ServerPort);
	error = getaddrinfo(ServerName, 0, &hints, &res0);
	if (error) {
		errx(1, "%s", gai_strerror(error));
	}

	/* Update server port. */
	int port = atoi(ServerPort);
	if (res0->ai_family == AF_INET6) {
		struct sockaddr_in6 *ipv6 = (struct sockaddr_in6*)res0->ai_addr;
		ipv6->sin6_port = htons(port);
	} else {
		struct sockaddr_in *ipv4 = (struct sockaddr_in*)res0->ai_addr;
		ipv4->sin_port = htons(port);
	}

	remote_len = res0->ai_addrlen;
	memcpy(&remote, res0->ai_addr, res0->ai_addrlen);
	memset(&countrcode, 0, sizeof(countrcode));

	res_init();
	_res.options ^= ~RES_RECURSE;
	_res.options |= RES_AAONLY;

	for (i = 0; i < nQueries; i++) {
		Queries[i].sent_flag = 0;
		Queries[i].no = i;
	}

	FD_ZERO(&fdset0r);
	FD_ZERO(&fdset0w);
	nfds = 0;
	UpdateCurrentTime;
	start = current;
	finished = 0;

	for (;;) {
		UpdateCurrentTime;
		if ((min = UpdateQuery()) < 0)
			break;
		timeout.tv_sec = min / 1000000;
		timeout.tv_usec = min % 1000000;
		fdsetr = fdset0r;
		fdsetw = fdset0w;
		n = select(nfds, &fdsetr, &fdsetw, NULL, &timeout);
		if (n==-1) {
			perror("socket select failed - function query");
			return;
		}
		UpdateCurrentTime;
		for(i = 0; i < nQueries; i++) {
			q = &Queries[i];
			if (q->fd < 0 || !q->sent_flag)
				continue;
			if (FD_ISSET(q->fd, &fdsetw)) {
				tcp_send(q);
			} else if (FD_ISSET(q->fd, &fdsetr)) {
				tcp_receive(q);
			}
		}
	}
}
Beispiel #4
0
void *second_level_recv()
{
	int flag;
	unsigned char real_time[256];
	unsigned char second_data[6*1024];
	struct plc_struct *p;
	struct msg_remote sdata;
	int semid,shmid;
	int rc;
	int count;
	int fd;
	int length;
	char*shmaddr;
	char*ret;
	struct shm_local* shared;
	printf("	second level recv pthread\n");
	fd=tcp_connect();
	read_plcfile();
	length=sizeof(struct msg_remote)-sizeof(long);
	if((shmid=creatshm(1))==-1)
		exit(1);
	if((shmaddr=shmat(shmid,(char*)0,0))==(char*)-1)
	{
		perror("attch shared memory error\n");
		exit(1);
	}
	shared=(struct shm_local *)shmaddr;
	shared->written=0;
	if((semid=creatsem(1))==-1)
		exit(1);
	while(1)
	{
		flag=0;
		switch(real_time_data)
		{
			case 0:
//			printf("1\n");
			length=tcp_receive(fd,second_data);
			while(1)
			{
			//	printf("1\n");
				sem_p(semid);
				if(shared->written==0)
				{
					memcpy(shared->data,second_data,length);
					shared->length=length;
					shared->written=1;
					printf("	send shm data ok\n");
					flag=1;
				}
				sem_v(semid);
				if(flag==1)
				{
					sleep(second_rate);
					break;
				}
				else
				{
					usleep(100000);
					continue;
				}
			}
			break;
			case 1:
			sdata.mtype=2;
			length=tcp_receive(fd,second_data);
			length=real_time_select(second_data,real_time);
			sdata.length=length;
			if(rc=msgsnd(remote_msgid,(void*)&sdata,sizeof(struct msg_remote)-sizeof(long),0)==-1)
				exit(1);
			printf("	send real time msg ok\n");
			break;
		}
	}
	exit(1);

}
Beispiel #5
0
////////////////////////////////////////////////////////////////////////////
// MAIN ////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
///
/// Main program.
///
int main( int argc, char *argv[] )
{

    CvCapture *video;
    CvVideoWriter *writer;
    IplImage *frame;
    IplImage *hsv;
    char *win_name = "Source Frame";
    char key = 0;
    tcp_connection *con;
    int frame_count = 0, result;
    int i;
    max_frames = 5000;
    unsigned char *byte_stream;
 
    // register signal handler for SIGINT und SIGPIPE
    // the latter occurs if the server terminates the connection
    /*
    DEBUG_PRINT( DEBUG_NOTE, "registering signal" )
        if ( signal( SIGINT, sig_handler ) == SIG_ERR ||
             signal( SIGPIPE, sig_handler ) == SIG_ERR ) {
        fprintf( stderr, "failed to register signal handler.\n" );
        exit( 1 );
    }
    */
    parse_args( argc, argv );

    // open the capture source
    switch ( source ) {
    case SOURCE_FILE:
        video = cvCreateFileCapture( infilename );
        break;
    case SOURCE_CAM:
        video = cvCreateCameraCapture( camera );
        break;
    default:
        fprintf( stderr, "strange source\n" );
        exit( 1 );
    }

    if ( !video ) {
        fprintf( stderr, "unable to capture source\n" );
        exit( 1 );
    }
    // connect to remote host
    con = tcp_connection_create( host, port );
    if ( !con ) {
        fprintf( stderr, "unable to connect to %s, port %d\n", host,
                 port );
        exit( 1 );
    }
    printf( "Connected to %s, port %d.\n", host, port );

    frame = cvQueryFrame( video );
    if ( !frame ) {
        fprintf( stderr, "unable to capture video.\n" );
        exit( 1 );
    }
    number_of_frames++;

    if ( netimage_send_header( con, frame ) <= 0 ) {
        fprintf( stderr, "unable to send header information.\n" );
        exit( 1 );
    }

    printf
        ( "Sending image stream (%d x %d, depth %u, %d channels (size: %d bytes)).\n"
          "Press 'q' to abort.\n", frame->width, frame->height,
          frame->depth, frame->nChannels, frame->imageSize );

    // open capture file, if desired
    if ( output ) {

        strncat( outfilename, ".mpg", MAX_FILENAMELEN );

        writer =
            cvCreateVideoWriter( outfilename, atofourcc( fourcc ), fps,
                                 cvSize( frame->width, frame->height ),
                                 frame->nChannels > 1 ? 1 : 0 );
        if ( writer == NULL ) {
            fprintf( stderr, "unable to create output file '%s'\n",
                     outfilename );
/*             exit (1);*/
        } else
            printf( "Writing to output file '%s'.\n", outfilename );
    }

    // for fps measurement
    struct timeval current, last;
    unsigned int diff;	// time difference in usecs
    int x0 = 0, y0 = 0, width = 0, height = 0;
	
    gettimeofday(&last, NULL);
    
    // show first frame for region selection   
    //frame = cvQueryFrame( video );
    //cvNamedWindow( win_name, 1 );
    //cvShowImage( win_name, frame );
    //if (output)
    //   cvWriteFrame( writer, frame );

    // get input region   
    char* win_name2 = "First frame";
    params p;
    CvRect* r;
    int x1, y1, x2, y2;
    int region[4];

  /* use mouse callback to allow user to define object regions */
  /*p.win_name = win_name2;
  p.orig_img = cvClone( frame );
  p.cur_img = NULL;
  p.n = 0;

  cvNamedWindow( win_name2, 1 );
  cvShowImage( win_name2, frame );
  cvSetMouseCallback( win_name2, &mouse, &p );
  printf("\nSelect Object and press [ENTER] !\n");
  cvWaitKey( 0 );

  cvDestroyWindow( win_name2 );
  cvReleaseImage( &p.orig_img );
  if( p.cur_img )
      cvReleaseImage( &(p.cur_img) );*/

  /* extract regions defined by user; store as an array of rectangles */
  if( p.n > 0 ){
      p.loc1[0].x = 0;
      p.loc1[0].y = 0;
      p.loc2[0].x = 0;
      p.loc2[0].y = 0;

      r = malloc(  sizeof( CvRect ) );
      x1 = MIN( p.loc1[0].x, p.loc2[0].x );
      x2 = MAX( p.loc1[0].x, p.loc2[0].x );
      y1 = MIN( p.loc1[0].y, p.loc2[0].y );
      y2 = MAX( p.loc1[0].y, p.loc2[0].y );
      width = x2 - x1;
      height = y2 - y1;

      /* ensure odd width and height */
      width = ( width % 2 )? width : width+1;
      height = ( height % 2 )? height : height+1;
      r[0] = cvRect( x1, y1, width, height );
      x0 = x1 + width/2;
      y0 = y1 + height/2;

      region[0] = x0;
      region[1] = y0;
      region[2] = width;
      region[3] = height;
   }


    //printf("\nx = %d\ny = %d\nwidth = %d\nheight = %d\n\n\n", x0, y0, width, height);

    // 1) convert bgr frame to hsv frame
    hsv = cvCreateImage( cvGetSize(frame), IPL_DEPTH_8U, 3 );
    bgr2hsv(frame, hsv);  
    result = tcp_send( con, hsv->imageData, hsv->imageSize);
    int counter = 1;
    //result = tcp_send( con, frame->imageData, frame->imageSize );

    result = tcp_send( con, (char *) region, 4 * sizeof(int));

    // confirm input with enter
    //printf("\nPress [ENTER]\n");
    //cvWaitKey( 0 );

    // TODO: send first frame + region data 
    //result = tcp_send( con, frame->imageData, frame->imageSize);
  
    number_of_particles = 100;

    // create particles data array
    particles_data = (particle_data *) malloc ((number_of_particles+1) * sizeof(particle_data));

    // quiet mode: no video output
    if (quiet){

         cvDestroyWindow( win_name );
    }

    // 1) send other frames
    // get video data and send/store it
#ifdef STORE_VIDEO
    //while ( ( frame = cvQueryFrame( video ) ) && ( char ) key != 'q' && !quit && number_of_frames <= 221 ) {
    while ( ( frame = cvQueryFrame( video ) ) && ( char ) key != 'q' && counter < max_frames) {
#else
    while ( ( frame = cvQueryFrame( video ) ) && ( char ) key != 'q' && counter < max_frames) {
#endif
        
        // 1) convert bgr frame to hsv frame
        bgr2hsv(frame, hsv); 
        result = tcp_send( con, hsv->imageData, hsv->imageSize );
        //fprintf(stderr, "\n///////////////////      number of frames %d     //////////////////////////////////////", number_of_frames);
        counter ++;
        //result = tcp_send( con, frame->imageData, frame->imageSize );

        if ( result > 0 ) {
            if ( !quiet ) {
                cvNamedWindow( win_name, 1 );

#ifdef NO_VGA_FRAMEBUFFER
#ifndef STORE_VIDEO          
	  if (number_of_frames > 2){
#else
 	  if (number_of_frames > 2 && number_of_frames % MAX_FRAMES == 0){
#endif
            // receive tcp package with particle data and display them in video
            // 1) receive tcp package with particles data
            //printf("\nreceive particles...");
            result = tcp_receive( con, (unsigned char*)particles_data, ((number_of_particles+1) * sizeof(particle_data)));
 
            if ( result > 0 ) {

               // 2) draw particles data         
               for (i=0; i<number_of_particles+1; i++){
         
	         // set OpenCV location points for bounding boxes
	         loc1.x = ntohl(particles_data[i].x1);
                 loc1.y = ntohl(particles_data[i].y1);
                 loc2.x = ntohl(particles_data[i].x2);
                 loc2.y = ntohl(particles_data[i].y2);
                 particles_data[i].best_particle = ntohl(particles_data[i].best_particle);

                 if (particles_data[i].best_particle > 0 ) particles_data[i].best_particle = TRUE;
                 
                 if (loc1.x <640 && loc2.x < 640 && loc1.y < 480 && loc2.y < 480)
                   // draw bounding box (red for best particle, blue else)
                   if (particles_data[i].best_particle == FALSE){
                 
                     cvRectangle( frame, loc1, loc2, CV_RGB(0,0,255), 1, 8, 0 ); 
                    } else {
                 
                      cvRectangle( frame, loc1, loc2, CV_RGB(255,0,0), 1, 8, 0 );   
                   }
	       }
             }
	   }        
#endif
                if (!quiet){
                  cvShowImage( win_name, frame );
                  //export_frame( frame, number_of_frames);
                  key = cvWaitKey( 2 );
                }
            }
            if ( output )
                cvWriteFrame( writer, frame );
        } else {
            printf( "connection lost.\n" );
            break;
        }
        //gettimeofday(&current, NULL);
        //diff = (current.tv_sec - last.tv_sec) * 1000000;
        //diff += (current.tv_usec - last.tv_usec);
	
        //fprintf(stderr, "FPS: %.2f\r", 1000000.0 / diff);
	
        //last.tv_sec = current.tv_sec;
        //last.tv_usec = current.tv_usec;
        number_of_frames++;
    }


/*
#ifdef STORE_VIDEO   
    cvReleaseCapture( &video );

    // 2) receive particle data and display particle data as Bounding Boxes
    switch ( source ) {
    case SOURCE_FILE:
        video = cvCreateFileCapture( infilename );
        break;
    case SOURCE_CAM:
        fprintf( stderr, "This part is only possible if video is stored into a file\n" );
        exit( 1 );
    default:
        fprintf( stderr, "strange source\n" );
        exit( 1 );
    }


    particles_data = malloc ((number_of_particles+1) * sizeof(particle_data));

    // get frames
    while ( ( frame = cvQueryFrame( video ) ) && ( char ) key != 'q' && !quit && number_of_frames <= 221 ) {


         // 1) receive tcp package with particles data
         // TODO
         result = tcp_receive( con, (char *)particles_data, ((number_of_particles+1) * sizeof(particle_data)));
 
         if ( result > 0 ) {

            // 2) draw particles data         
            for (i=0; i<number_of_particles+1; i++){
         
	         // set OpenCV location points for bounding boxes
	         loc1.x = particles_data[i].x1;
                 loc1.y = particles_data[i].y1;
                 loc2.x = particles_data[i].x2;
                 loc2.y = particles_data[i].y2;
                 
                 // draw bounding box (red for best particle, blue else)
                 if (particles_data[i].best_particle == TRUE){
                 
                    cvRectangle( frame, loc1, loc2, CV_RGB(255,0,0), 1, 8, 0 ); 
                 } else {
                 
                    cvRectangle( frame, loc1, loc2, CV_RGB(0,0,255), 1, 8, 0 );   
                 }
	    }
         }

         // display video frame
         if (!quiet){
              cvNamedWindow( win_name, 1 );
              cvShowImage( win_name, frame );
              key = cvWaitKey( 2 );
         }
         number_of_frames++;
    }
#endif
*/
    // clean up
    if (!quiet){

         cvDestroyWindow( win_name );
    }
    cvReleaseCapture( &video );
    if ( output )
        cvReleaseVideoWriter( &writer );
    tcp_connection_destroy( con );

    return 0;
}




/*
  Mouse callback function that allows user to specify the initial object
  regions.  Parameters are as specified in OpenCV documentation.
*/
void mouse( int event, int x, int y, int flags, void* param )
{
  params* p = (params*)param;
  CvPoint* loc;
  int n;
  IplImage* tmp;
  static int pressed = 0;
  
  /* on left button press, remember first corner of rectangle around object */
  if( event == CV_EVENT_LBUTTONDOWN )
    {
      n = p->n;
      if( n == 1 )
	return;
      loc = p->loc1;
      loc[n].x = x;
      loc[n].y = y;
      pressed = 1;
    }

  /* on left button up, finalize the rectangle and draw it in black */
  else if( event == CV_EVENT_LBUTTONUP )
    {
      n = p->n;
      if( n == 1 )
	return;
      loc = p->loc2;
      loc[n].x = x;
      loc[n].y = y;
      cvReleaseImage( &(p->cur_img) );
      p->cur_img = NULL;
      cvRectangle( p->orig_img, p->loc1[n], loc[n], CV_RGB(0,0,0), 1, 8, 0 );
      cvShowImage( p->win_name, p->orig_img );
      pressed = 0;
      p->n++;
    }

  /* on mouse move with left button down, draw rectangle as defined in white */
  else if( event == CV_EVENT_MOUSEMOVE  &&  flags & CV_EVENT_FLAG_LBUTTON )
    {
      n = p->n;
      if( n == 1 )
	return;
      tmp = cvClone( p->orig_img );
      loc = p->loc1;
      cvRectangle( tmp, loc[n], cvPoint(x, y), CV_RGB(255,255,255), 1, 8, 0 );
      cvShowImage( p->win_name, tmp );
      if( p->cur_img )
	cvReleaseImage( &(p->cur_img) );
      p->cur_img = tmp;
    }
}
Beispiel #6
0
/**
 * Implements the TCP state machine. Called by tcp_input. In some
 * states tcp_receive() is called to receive data. The tcp_seg
 * argument will be freed by the caller (tcp_input()) unless the
 * recv_data pointer in the pcb is set.
 *
 * @param pcb the tcp_pcb for which a segment arrived
 *
 * @note the segment which arrived is saved in global variables, therefore only the pcb
 *       involved is passed as a parameter to this function
 */
static err_t
tcp_process(struct tcp_pcb *pcb)
{
  struct tcp_seg *rseg;
  u8_t acceptable = 0;
  err_t err;
  u8_t accepted_inseq;

  err = ERR_OK;

  /* Process incoming RST segments. */
  if (flags & TCP_RST) {
    /* First, determine if the reset is acceptable. */
    if (pcb->state == SYN_SENT) {
      if (ackno == pcb->snd_nxt) {
        acceptable = 1;
      }
    } else {
      if (TCP_SEQ_BETWEEN(seqno, pcb->rcv_nxt,
                          pcb->rcv_nxt+pcb->rcv_ann_wnd)) {
        acceptable = 1;
      }
    }

    if (acceptable) {
      LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_process: Connection RESET\n"));
      LWIP_ASSERT("tcp_input: pcb->state != CLOSED", pcb->state != CLOSED);
      recv_flags = TF_RESET;
      pcb->flags &= ~TF_ACK_DELAY;
      return ERR_RST;
    } else {
      LWIP_DEBUGF(TCP_INPUT_DEBUG, ("tcp_process: unacceptable reset seqno %"U32_F" rcv_nxt %"U32_F"\n",
       seqno, pcb->rcv_nxt));
      LWIP_DEBUGF(TCP_DEBUG, ("tcp_process: unacceptable reset seqno %"U32_F" rcv_nxt %"U32_F"\n",
       seqno, pcb->rcv_nxt));
      return ERR_OK;
    }
  }

  /* Update the PCB (in)activity timer. */
  pcb->tmr = tcp_ticks;
  pcb->keep_cnt_sent = 0;

  /* Do different things depending on the TCP state. */
  switch (pcb->state) {
  case SYN_SENT:
    LWIP_DEBUGF(TCP_INPUT_DEBUG, ("SYN-SENT: ackno %"U32_F" pcb->snd_nxt %"U32_F" unacked %"U32_F"\n", ackno,
     pcb->snd_nxt, ntohl(pcb->unacked->tcphdr->seqno)));
    /* received SYN ACK with expected sequence number? */
    if ((flags & TCP_ACK) && (flags & TCP_SYN)
        && ackno == ntohl(pcb->unacked->tcphdr->seqno) + 1) {
      pcb->snd_buf++;
      pcb->rcv_nxt = seqno + 1;
      pcb->lastack = ackno;
      pcb->snd_wnd = tcphdr->wnd;
      pcb->snd_wl1 = seqno - 1; /* initialise to seqno - 1 to force window update */
      pcb->state = ESTABLISHED;

      /* Parse any options in the SYNACK before using pcb->mss since that
       * can be changed by the received options! */
      tcp_parseopt(pcb);
#if TCP_CALCULATE_EFF_SEND_MSS
      pcb->mss = tcp_eff_send_mss(pcb->mss, &(pcb->remote_ip));
#endif /* TCP_CALCULATE_EFF_SEND_MSS */

      /* Set ssthresh again after changing pcb->mss (already set in tcp_connect
       * but for the default value of pcb->mss) */
      pcb->ssthresh = pcb->mss * 10;

      pcb->cwnd = ((pcb->cwnd == 1) ? (pcb->mss * 2) : pcb->mss);
      LWIP_ASSERT("pcb->snd_queuelen > 0", (pcb->snd_queuelen > 0));
      --pcb->snd_queuelen;
      LWIP_DEBUGF(TCP_QLEN_DEBUG, ("tcp_process: SYN-SENT --queuelen %"U16_F"\n", (u16_t)pcb->snd_queuelen));
      rseg = pcb->unacked;
      pcb->unacked = rseg->next;

      /* If there's nothing left to acknowledge, stop the retransmit
         timer, otherwise reset it to start again */
      if(pcb->unacked == NULL)
        pcb->rtime = -1;
      else {
        pcb->rtime = 0;
        pcb->nrtx = 0;
      }

      tcp_seg_free(rseg);

      /* Call the user specified function to call when sucessfully
       * connected. */
      TCP_EVENT_CONNECTED(pcb, ERR_OK, err);
      tcp_ack_now(pcb);
    }
    /* received ACK? possibly a half-open connection */
    else if (flags & TCP_ACK) {
      /* send a RST to bring the other side in a non-synchronized state. */
      tcp_rst(ackno, seqno + tcplen, &(iphdr->dest), &(iphdr->src),
        tcphdr->dest, tcphdr->src);
    }
    break;
  case SYN_RCVD:
    if (flags & TCP_ACK &&
       !(flags & TCP_RST)) {
      /* expected ACK number? */
      if (TCP_SEQ_BETWEEN(ackno, pcb->lastack+1, pcb->snd_nxt)) {
        u16_t old_cwnd;
        pcb->state = ESTABLISHED;
        LWIP_DEBUGF(TCP_DEBUG, ("TCP connection established %"U16_F" -> %"U16_F".\n", inseg.tcphdr->src, inseg.tcphdr->dest));
#if LWIP_CALLBACK_API
        LWIP_ASSERT("pcb->accept != NULL", pcb->accept != NULL);
#endif
        /* Call the accept function. */
        TCP_EVENT_ACCEPT(pcb, ERR_OK, err);
        if (err != ERR_OK) {
          /* If the accept function returns with an error, we abort
           * the connection. */
          tcp_abort(pcb);
          return ERR_ABRT;
        }
        old_cwnd = pcb->cwnd;
        /* If there was any data contained within this ACK,
         * we'd better pass it on to the application as well. */
        accepted_inseq = tcp_receive(pcb);

        pcb->cwnd = ((old_cwnd == 1) ? (pcb->mss * 2) : pcb->mss);

        if ((flags & TCP_FIN) && accepted_inseq) {
          tcp_ack_now(pcb);
          pcb->state = CLOSE_WAIT;
        }
      }
      /* incorrect ACK number */
      else {
        /* send RST */
        tcp_rst(ackno, seqno + tcplen, &(iphdr->dest), &(iphdr->src),
                tcphdr->dest, tcphdr->src);
      }
    }
    break;
  case CLOSE_WAIT:
    /* FALLTHROUGH */
  case ESTABLISHED:
    accepted_inseq = tcp_receive(pcb);
    if ((flags & TCP_FIN) && accepted_inseq) { /* passive close */
      tcp_ack_now(pcb);
      pcb->state = CLOSE_WAIT;
    }
    break;
  case FIN_WAIT_1:
    tcp_receive(pcb);
    if (flags & TCP_FIN) {
      if (flags & TCP_ACK && ackno == pcb->snd_nxt) {
        LWIP_DEBUGF(TCP_DEBUG,
          ("TCP connection closed %"U16_F" -> %"U16_F".\n", inseg.tcphdr->src, inseg.tcphdr->dest));
        tcp_ack_now(pcb);
        tcp_pcb_purge(pcb);
        TCP_RMV(&tcp_active_pcbs, pcb);
        pcb->state = TIME_WAIT;
        TCP_REG(&tcp_tw_pcbs, pcb);
      } else {
        tcp_ack_now(pcb);
        pcb->state = CLOSING;
      }
    } else if (flags & TCP_ACK && ackno == pcb->snd_nxt) {
      pcb->state = FIN_WAIT_2;
    }
    break;
  case FIN_WAIT_2:
    tcp_receive(pcb);
    if (flags & TCP_FIN) {
      LWIP_DEBUGF(TCP_DEBUG, ("TCP connection closed %"U16_F" -> %"U16_F".\n", inseg.tcphdr->src, inseg.tcphdr->dest));
      tcp_ack_now(pcb);
      tcp_pcb_purge(pcb);
      TCP_RMV(&tcp_active_pcbs, pcb);
      pcb->state = TIME_WAIT;
      TCP_REG(&tcp_tw_pcbs, pcb);
    }
    break;
  case CLOSING:
    tcp_receive(pcb);
    if (flags & TCP_ACK && ackno == pcb->snd_nxt) {
      LWIP_DEBUGF(TCP_DEBUG, ("TCP connection closed %"U16_F" -> %"U16_F".\n", inseg.tcphdr->src, inseg.tcphdr->dest));
      tcp_ack_now(pcb);
      tcp_pcb_purge(pcb);
      TCP_RMV(&tcp_active_pcbs, pcb);
      pcb->state = TIME_WAIT;
      TCP_REG(&tcp_tw_pcbs, pcb);
    }
    break;
  case LAST_ACK:
    tcp_receive(pcb);
    if (flags & TCP_ACK && ackno == pcb->snd_nxt) {
      LWIP_DEBUGF(TCP_DEBUG, ("TCP connection closed %"U16_F" -> %"U16_F".\n", inseg.tcphdr->src, inseg.tcphdr->dest));
      /* bugfix #21699: don't set pcb->state to CLOSED here or we risk leaking segments */
      recv_flags = TF_CLOSED;
    }
    break;
  default:
    break;
  }
  return ERR_OK;
}
Beispiel #7
0
char SyncTime(char *msg)
{
	unsigned char buff[100]={0};
	unsigned char timezone;
        unsigned int year = 0;
        unsigned char year_H= 20;
        unsigned char year_L= 0;
        unsigned char month = 0;
        unsigned char day = 0;
        unsigned char hour = 0;
        unsigned char minute = 0;
        unsigned char second = 0;
	char YearofMonth[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
	char *p=NULL;

	clear_lcd();
	DrawTitle_to_row_Language2(2,"同步时间中","Sync time"); 		
	DrawTitle_to_row_Language2(3,"请稍等...","Please wait...");

    sprintf((char*)buff,"AT+QNTP=\"%s\",123\r",TimeServer);
	printf("buff:<%s>\r\n",buff);
	kmy_USART2SendString(buff);
	memset(buff,0,sizeof(buff));
	if(tcp_receive(buff,sizeof(buff),"+QNTP:",180)!=TCP_ReceiveOK) goto FailExit;
	if(strstr((char*)buff,"+QNTP: 0")==NULL) goto FailExit;
	
	kmy_USART2SendString("AT+CCLK?\r");
	printf("AT+CCLK?\r");
	if(tcp_receive(buff,sizeof(buff),"+CCLK:",10)!=TCP_ReceiveOK) goto FailExit;
	printf("buff:<%s>\r\n",buff);

//+CCLK: "14/05/30,09:36:29+00"	
        p=(char*)buff;
	p=strchr(p,'"');
	if(p==NULL)goto FailExit;
	p++;
	year_L=atoi(p);
	printf("year_L:<%d>\r\n",year_L);
	
	p=strchr(p,'/');
	if(p==NULL)goto FailExit;
	p++;
	month=atoi(p);
	printf("month:<%d>\r\n",month);

	p=strchr(p,'/');
	if(p==NULL)goto FailExit;
	p++;
	day=atoi(p);
	printf("day:<%d>\r\n",day);

	p=strchr(p,',');
	if(p==NULL)goto FailExit;
	p++;
	hour =atoi(p);
	printf("hour:<%d>\r\n",hour);

	p=strchr(p,':');
	if(p==NULL)goto FailExit;
	p++;
	minute=atoi(p);
	printf("minute:<%d>\r\n",minute);

	p=strchr(p,':');
	if(p==NULL)goto FailExit;
	p++;
	second=atoi(p);
	printf("second:<%d>\r\n",second);

	if(strchr((char*)TimeZone,'+'))
	{
		p=strchr((char*)TimeZone,'+');
		if(p!=NULL)
		{
			p++;
			timezone=atoi(p);
			hour+=timezone;
		}
		if(hour>=24)
		{
			hour-=24;
			day++;
		}
		
		year=year_H*100+year_L;
		
		if(day>YearofMonth[month])
		{
			 if(month==2)
			 {
				   if(year%4==0&&year%100!=0||year%400==0)
				   {
					   if(day>29)month++;
					   day=1;
				   }
				   else
				   {
					   month++;
					   day=1;
				   }
			 }
			 else
			 {
				   month++;
				   day=1;
			 }
		}
		
		if(month>12)
		{
			month=1;
			year++;
		}
	}
	else
	{
		p=strchr((char*)TimeZone,'-');
		if(p!=NULL)
		{
			p++;
			timezone=atoi(p);
			if(hour>=timezone)hour-=timezone;
			else
			{
				hour=24-(timezone-hour);
				day--;
			}
		}

		year=year_H*100+year_L;
		if(day==0)
		{
			month--;
			if(month==0)
			{
				month=12;
				year--;
			}	
			if(month==2)
			{
				   if(year%4==0&&year%100!=0||year%400==0)
				   {
					   day=29;
				   }
				   else
				   {
					   day=YearofMonth[month];
				   }
			 }
			 else
			 {
				   day=YearofMonth[month];
			 }
		}
	}	

	printf("Time:%4d-%02d-%02d %02d:%02d:%02d",year,month,day,hour,minute,second);
	kmy_TimeSetTime (year, month, day, hour, minute, second);
	clear_lcd();
	DrawTitle_to_row_Language2(2,"同步时间成功!","Sync time success"); 
	return WaitkeyAndAutoExit(5);	
		
FailExit:	
	printf("buff:<%s>\r\n",buff);
	clear_lcd();
	DrawTitle_to_row_Language2(2,"同步时间失败!","Sync time fail"); 
	return WaitkeyAndAutoExit(5);
}