Esempio n. 1
0
void cmd_remote_handler( int rc, int sock ) {
	char* argv[32];
	int argc;

	IP clientaddr;
	socklen_t addrlen_ret;
	socklen_t addrlen;
	char request[1500];
	REPLY reply;

	addrlen_ret = sizeof(IP);
	rc = recvfrom( sock, request, sizeof(request) - 1, 0, (struct sockaddr*)&clientaddr, &addrlen_ret );
	if( rc <= 0 ) {
		return;
	} else {
		request[rc] = '\0';
	}

	/* Initialize reply and reserve room for return status */
	r_init( &reply, false );
	r_printf( &reply, "_" );

	/* Split up the command line into an argument array */
	cmd_to_args( request, &argc, &argv[0], N_ELEMS(argv) );

	/* Execute command line */
	rc = cmd_exec( &reply, argc, argv );

	/* Insert return code */
	reply.data[0] = (rc == 0) ? '0' : '1';

	addrlen = addr_len( &clientaddr );
	rc = sendto( sock, reply.data, reply.size, 0, (struct sockaddr *)&clientaddr, addrlen );
}
Esempio n. 2
0
void cmd_console_handler( int rc, int fd ) {
	char request[512];
	char *req;
	REPLY reply;
	char *argv[32];
	int argc;

	if( rc == 0 ) {
		return;
	}

	/* Read line */
	req = fgets( request, sizeof(request), stdin );

	if( req == NULL ) {
		return;
	}

	/* Split up the command line into an argument array */
	cmd_to_args( request, &argc, &argv[0], N_ELEMS(argv) );

	/* Initialize reply */
	r_init( &reply, true );

	/* Execute command line */
	rc = cmd_exec( &reply, argc, argv );

	if( rc == 0 ) {
		fprintf( stdout, "%.*s\n", (int) reply.size, reply.data );
	} else {
		fprintf( stderr, "%.*s\n", (int) reply.size, reply.data );
	}
}
Esempio n. 3
0
uint8_t calcula_r (struct res *r)
{
	uint16_t adcval=0;
	
	// pins a alta impedancia
	r_init();
	
		// mirem vin amb r1 a vcc
	OUTPUT_H(RM1);
	_delay_ms(100);
	adcval = ReadAdc(RVIN);
	OUTPUT_Z(RM1);

    if (adcval <= VAL)
	{
		r->valor = formula_r(adcval, 1);
		return 1;
	}
	
	// mirem vin amb r2 a vcc
	OUTPUT_H(RM2);
	_delay_ms(100);
	adcval = ReadAdc(RVIN);
	OUTPUT_Z(RM2);
	if (adcval <= VAL) 
	{
		r->valor = formula_r(adcval, 2);
		return 2;
	}
	
	// mirem vin amb r3 a vcc
	OUTPUT_H(RM3);
	_delay_ms(100);
	adcval = ReadAdc(RVIN);
	OUTPUT_Z(RM3);
	if (adcval <= VAL) 
	{
		r->valor = formula_r(adcval, 3);
		return 3;
	}
	
	// mirem vin amb r4 a vcc
	OUTPUT_H(RM4);
	_delay_ms(100);
	adcval = ReadAdc(RVIN);
	OUTPUT_Z(RM4);
	if ( adcval < VAL ) 
	{
		r->valor = formula_r(adcval, 4);
		return 4;
	}
	
	return 10;

}
Esempio n. 4
0
int main (int argc, char* argv[]) {
	SDL_Event		event;
	SDL_Surface		*screen;

	if (SDL_Init (SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0) {
		printf ("Unable to initialize SDL: %s\n", SDL_GetError ());
		return 1;
	}

	SDL_WM_SetCaption ("Cube of cubes", "Cube of cubes");
	SDL_ShowCursor(SDL_DISABLE);
	SDL_GL_SetAttribute (SDL_GL_DOUBLEBUFFER, 1);

	//Initialize window
	screen = SDL_SetVideoMode (WINDOW_WIDTH, WINDOW_HEIGHT, 32, SDL_OPENGL);
	if (!screen) {
		printf ("Unable to set video mode: %s\n", SDL_GetError ());
		return 1;
	}

	r_init ();

	//Main loop
	while (!user_exit) {
		//Handle input
		while (SDL_PollEvent (&event)) {
			switch (event.type) {
			case SDL_KEYDOWN:
				input_keyDown (event.key.keysym.sym);
				break;
			case SDL_KEYUP:
				input_keyUp (event.key.keysym.sym);
				break;
			case SDL_MOUSEMOTION:
				input_mouseMove (event.motion.x, event.motion.y);
				break;
			case SDL_QUIT:
				exit (0);
			}
		}
		input_update ();
		r_drawFrame ();
		// Cap it at 100 fps
		usleep (10000);
	}

	SDL_Quit ();

	return 0;
}
Esempio n. 5
0
int main( int argc, char** argv)
{
	///< Init
	r_init( Center_Node);
	r_hdlr( hdl);
	ros::Rate loop_rate( 10);

	///< Publisher
	r_newPub( motpub, hdl, challenge1::Motor, Arduino_Motor, 1000);
	
	///< Subscriber
	r_newSub( irtsub, hdl, Arduino_IR_trigger, 1000, btracker);
	r_newSub( trafsub, hdl, traf_color, 1000, trafColor);
	r_newSub( usonicsub, hdl, Arduino_Ultrasonic, 1000, avoidance);
	r_newSub( roadsub, hdl, Road, 1000, rddirect);

	///< Msg init
	//challenge1::trafficLight traf;
	traf.color = 0;

	///< State Control
	fcntl( 0, F_SETFL, O_NONBLOCK);/*///< make the stdin be nonblocking*/
	optMotor( motStop, stop);

	char tmpc = 'r';

	///< while loop
	while( ros::ok())
	{
		if( retKey())
			tmpc = *key;

		switch( tmpc){
			case( STOP):
				motpub.publish( motStop);
				break;
			case( RUN):
			default:
				motpub.publish( mot);
				break;
		}
		

		ros::spinOnce();
		loop_rate.sleep();
	}
}
Esempio n. 6
0
// Programa principal
int main(void)
{
   	//Inicialitza el display LCD
   	LCDInit(LS_NONE);
     
   	//Neteja la pantalla
   	LCDClear();
    
   	//Inicialitza el comptador
   	freq_counter_init();

   	// inicialitza el mesurador de inductancia i capacitat
   	LC_init();

   	//inicialitza el mesurador de transistors
   	tr_init();

   	//inicialitza el mesurador de resistencia
   	r_init();

   	//inicialitza els polsadors i les interrupcions d'aquets
   	polsadors_init();

	
   	// inicialitza el menu del lcd
	menu_init();
   	while(1)
   	{
		if (flag_polsador == 1)
		{
			flag_polsador = 0;
    		menu(polsador);
		}
	}

   return 0;
}
Esempio n. 7
0
/*
 * SDL_main
 * Program entry point.
 */
int main(int argc, char* argv[])
{
	size = 32;
	srand(time(NULL));
	SDL_Event	event;
	SDL_Surface	*screen;

	if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0)
	{
		printf("Unable to initialize SDL: %s\n", SDL_GetError());
		return 1;
	}

	SDL_WM_SetCaption("Camera Demo", "Camera Demo");
	SDL_ShowCursor(SDL_DISABLE);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	screen = SDL_SetVideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, 32, SDL_OPENGL);
	if(!screen)
	{
		printf("Unable to set video mode: %s\n", SDL_GetError());
		return 1;
	}

	r_init();

	float t = 0.0f;
	float dt = 0.1f;

	float currentTime = 0.0f;
	float accumulator = 0.0f;

	while(!user_exit)
	{
		if (won) {
			r_init();
		}
		float newTime = time(0);
		float deltaTime = newTime - currentTime;
		currentTime = newTime;

		if (deltaTime>0.25f)
			deltaTime = 0.25f;

		accumulator += deltaTime;

		while (accumulator>=dt)
		{
			accumulator -= dt;
			t += dt;
		}

		//Handle input
		while(SDL_PollEvent(&event))
		{
			switch(event.type)
			{
			case SDL_KEYDOWN:
				input_keyDown(event.key.keysym.sym);
				break;
			case SDL_KEYUP:
				input_keyUp(event.key.keysym.sym);
				break;
			case SDL_MOUSEMOTION:
				input_mouseMove(event.motion.x, event.motion.y);
				break;
			case SDL_QUIT:
				user_exit = 1;
			}
		}

		input_update();

		r_drawFrame();
	}

	SDL_Quit();
	return 0;
}
Esempio n. 8
0
//Program entry point
int SDL_main(int argc, char* argv[])
{
	int i;
	SDL_Event	event;		//Used for handling input events, as you can see later on.
	SDL_Surface	*screen;	//http://www.libsdl.org/cgi/docwiki.cgi/SDL_Surface
	CAMERA_POSITION camera;
	float *colors[3] = {&RED[0], &GREEN[0], &BLUE[0]};

	for (i = 0; i < 256; i++) {
		keys_down[i] = 0;
	}
	resetCamera(&camera);

	//The following is pretty self-explanatory
	if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0)
	{
		printf("Unable to initialize SDL: %s\n", SDL_GetError());
		return 1;
	}

	//You can of course customize this.
	SDL_WM_SetCaption("Perspective Projection", "Perspective Projection");

	//We need to explicitly enable double buffering
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	//Initialize window, setting the resolution to 1024x768 @ 32 bits per pixel. We want an OpenGL window.
	screen = SDL_SetVideoMode(1024, 768, 32, SDL_OPENGL);
	if(!screen)
	{
		printf("Unable to set video mode: %s\n", SDL_GetError());
		return 1;
	}

	//Any other one-time initialization would typically go here.
	//"Renderer" initialization
	r_init(&camera);

	//This is what is referred to as the "game loop." Obviously there is not much here currently.
	while(!user_exit)
	{
		bool mouseMoved = FALSE;
		int x = 0, y = 0;
		//Handle input
		while(SDL_PollEvent(&event))
		{
			switch(event.type)
			{
			case SDL_KEYDOWN:
				input_keyDown(event.key.keysym.sym, &camera);
				break;
			case SDL_KEYUP:
				input_keyUp(event.key.keysym.sym);
				break;
			case SDL_MOUSEBUTTONDOWN:
				randomizeColors(colors);
				break;
			case SDL_MOUSEMOTION:
				x = event.motion.x;
				y = event.motion.y;
				mouseMoved = TRUE;
				break;
			case SDL_QUIT:
				exit(0);
			}
		}
		input_update(&camera);
		if (mouseMoved) {
			input_mouseMoved(&camera, x, y);
			setUpAndLoadModelViewMatrix(&camera);
		}

		//Here is where you will do any OpenGL drawing. You would also do things like update moving objects, etc.
		//Do whatever we need to do to draw a single image.
		r_drawFrame(colors);
	}

	//Shut down SDL
	SDL_Quit();

	//Everything went OK.
	return 0;
}
Esempio n. 9
0
int main(int argc, char *argv[]) {
	// Check command arguments
	int c;
	int DEVICE, SEGMENTATION_RATIO, OFFSET, ANGLE, THRESHOLD, RESOLUTION;
	while ((c = getopt(argc, argv, "v:s:o:a:t:r:")) != -1) {
		switch (c) {
			case 'v':
				DEVICE = atoi(optarg);
				break;
			case 's':
				SEGMENTATION_RATIO = atoi(optarg);
				break;
			case 'o':
				OFFSET = atoi(optarg);
				break;
			case 'a':
				ANGLE = atoi(optarg);
				break;
			case 't':
				THRESHOLD = atoi(optarg);
				break;
			case 'r':
				RESOLUTION = atoi(optarg);
				break;
			default: // '?'
				std::cout << "Usage: " << argv[0] << " [-v device] [-s segmentation_ratio] [-o offset] [-a angle] [-t threshold] [-r resolution]" << std::endl;
				return -1;
		}
	}
	if (argc != 13) {
		std::cout << "Usage: " << argv[0] << " [-v device] [-s segmentation_ratio] [-o offset] [-a angle] [-t threshold] [-r resolution]" << std::endl;
		return -1;
	}

	/*ROS*/
	r_init( Road_Detecter);
	r_hdlr( hdl);
	r_newPub( pubRoad, hdl, challenge1::road, Road, 1000);
	ros::Rate loop_rate(10);

	challenge1::road rd;
	/**/

	cv::VideoCapture myVideoCapture(DEVICE);
	if (!myVideoCapture.isOpened()) {
		std::cout << "ERROR: Cannot open device " << DEVICE << std::endl;
		return -1;
	}

	cv::namedWindow("Video Captured");
	cv::namedWindow("Road Detected");

	int imgCenter = myVideoCapture.get(CV_CAP_PROP_FRAME_WIDTH) / 2;
	int preCenter = imgCenter;
	int movingDirection = GO_STRAIGHT;
	//while (1) {
	while( ros::ok()){
		int key = cv::waitKey(1);
		if ((key & 0xFF) == 27) // 'Esc' key
			return 0;

		cv::Mat inputFrame, segmentedInputFrame;
		myVideoCapture >> inputFrame;
		inputFrame(cv::Range(inputFrame.rows - inputFrame.rows / SEGMENTATION_RATIO, inputFrame.rows - 1), cv::Range::all()).copyTo(segmentedInputFrame);

		// Detect road. In general, there are only vertical lines
		cv::Mat road = detectRoad(segmentedInputFrame, OFFSET, ANGLE);

		// Compute the road center
		int curCenter = computeCenter(road);

		// Compute the moving direction
		movingDirection = computeMovingDirection(imgCenter, preCenter, curCenter, movingDirection, THRESHOLD, RESOLUTION);
		std::cout << movingDirection << std::endl;

		cv::imshow("Video Captured", segmentedInputFrame);
		cv::imshow("Road Detected", road);

		/*ROS*/
		/*switch( movingDirection){
			case GO_STRAIGHT:
			case TURN_LEFT:
			case TURN_RIGHT:
			default:
				break;
		}*/
		rd.direction = movingDirection;

		pubRoad.publish( rd);
		ros::spinOnce();
		loop_rate.sleep();
		/*\ROS*/
	}

	return 0;
}
Esempio n. 10
0
int main(int argc, char *argv[])
{
    #include "setRootCase.H"
    #include "createTime.H"
    #include "createMesh.H"

    Info << "Reading T_init" << endl;
    volScalarField T_init
    (
        IOobject("T_init", runTime.constant(), mesh, IOobject::MUST_READ),
        mesh
    );
    
    Info << "Reading P_init" << endl;
    volScalarField P_init
    (
        IOobject("P_init", runTime.constant(), mesh, IOobject::MUST_READ),
        mesh
    );

    Info << "Reading rt_init" << endl;
    volScalarField rt_init
    (
        IOobject("rt_init", runTime.constant(), mesh, IOobject::MUST_READ),
        mesh
    );
    
    Info << "Reading r_init" << endl;
    volScalarField r_init
    (
        IOobject("r_init", runTime.constant(), mesh, IOobject::MUST_READ),
        mesh
    );

    Info << "Reading or creating tracer field rhof_init" << endl;
    surfaceScalarField rhof_init
    (
        IOobject("rhof_init", runTime.constant(), mesh, IOobject::READ_IF_PRESENT),
        linearInterpolate(rt_init)
    );
    
    Info << "Creating T" << endl;
    volScalarField T
    (
        IOobject("T", runTime.timeName(), mesh, IOobject::NO_READ),
        T_init
    );
    
    Info << "Creating P" << endl;
    volScalarField P
    (
        IOobject("P", runTime.timeName(), mesh, IOobject::NO_READ),
        P_init
    );
    
    Info << "Creating rt" << endl;
    volScalarField rt
    (
        IOobject("rt", runTime.timeName(), mesh, IOobject::NO_READ),
        rt_init
    );

    Info << "Creating rl" << endl;
    volScalarField rl
    (
        IOobject("rl", runTime.timeName(), mesh, IOobject::NO_READ),
        r_init
    );

    Info << "Creating rv" << endl;
    volScalarField rv
    (
        IOobject("rv", runTime.timeName(), mesh, IOobject::NO_READ),
        r_init
    );
    
    Info << "Creating rl_diag" << endl;
    volScalarField rl_diag
    (
        IOobject("rl_diag", runTime.timeName(), mesh, IOobject::NO_READ),
        r_init
    );

    Info << "Creating rv_diag" << endl;
    volScalarField rv_diag
    (
        IOobject("rv_diag", runTime.timeName(), mesh, IOobject::NO_READ),
        r_init
    );
    
    Info << "Creating rl_analytic" << endl;
    volScalarField rl_analytic
    (
        IOobject("rl_analytic", runTime.timeName(), mesh, IOobject::NO_READ),
        r_init
    );
    
    Info << "Creating rv_analytic" << endl;
    volScalarField rv_analytic
    (
        IOobject("rv_analytic", runTime.timeName(), mesh, IOobject::NO_READ),
        r_init
    );
    
    Info << "Creating rt_analytic" << endl;
    volScalarField rt_analytic
    (
        IOobject("rt_analytic", runTime.timeName(), mesh, IOobject::NO_READ),
        r_init
    );
    
    Info << "Creating S" << endl;
    volScalarField S
    (
        IOobject("S", runTime.timeName(), mesh, IOobject::NO_READ),
        r_init
    );

    Info << "Creating rhof" << endl;
    surfaceScalarField rhof
    (
        IOobject("rhof", runTime.timeName(), mesh, IOobject::NO_READ),
        rhof_init
    );

    IOdictionary rtDict
    (
        IOobject
        (
            "totalMoistureDict",
            mesh.time().system(),
            mesh,
            IOobject::READ_IF_PRESENT,
            IOobject::NO_WRITE
        )
    );
    
    IOdictionary rlDict
    (
        IOobject
        (
            "liquidWaterDict",
            mesh.time().system(),
            mesh,
            IOobject::READ_IF_PRESENT,
            IOobject::NO_WRITE
        )
    );
    
    IOdictionary rvDict
    (
        IOobject
        (
            "waterVapourDict",
            mesh.time().system(),
            mesh,
            IOobject::READ_IF_PRESENT,
            IOobject::NO_WRITE
        )
    );
    
    IOdictionary tempDict
    (
        IOobject
        (
            "tempDict",
            mesh.time().system(),
            mesh,
            IOobject::READ_IF_PRESENT,
            IOobject::NO_WRITE
        )
    );
    
    IOdictionary PDict
    (
        IOobject
        (
            "pressureDict",
            mesh.time().system(),
            mesh,
            IOobject::READ_IF_PRESENT,
            IOobject::NO_WRITE
        )
    );

    const noAdvection velocityField;
    autoPtr<tracerField> rtVal(tracerField::New(rtDict, velocityField));
    
    autoPtr<tracerField> rlVal(tracerField::New(rlDict, velocityField));
    
    autoPtr<tracerField> rvVal(tracerField::New(rvDict, velocityField));
    
    autoPtr<tracerField> tempVal(tracerField::New(tempDict, velocityField));
    
    autoPtr<tracerField> PVal(tracerField::New(PDict, velocityField));
    
    Info << "writing rt for time " << runTime.timeName() << endl;
    rtVal->applyTo(rt);
    rt.write();
    
    Info << "writing rl for time " << runTime.timeName() << endl;
    rlVal->applyTo(rl);
    rl.write();

    Info << "writing rv for time " << runTime.timeName() << endl;
    rvVal->applyTo(rv);
    rv.write();
    
    Info << "writing rl_diag for time " << runTime.timeName() << endl;
    rlVal->applyTo(rl_diag);
    rl_diag.write();

    Info << "writing rv_diag for time " << runTime.timeName() << endl;
    rvVal->applyTo(rv_diag);
    rv_diag.write();

    Info << "writing rl_analytic for time " << runTime.timeName() << endl;
    rlVal->applyTo(rl_analytic);
    rl_analytic.write();
    
    Info << "writing rv_analytic for time " << runTime.timeName() << endl;
    rvVal->applyTo(rv_analytic);
    rv_analytic.write();

    Info << "writing rt_analytic for time " << runTime.timeName() << endl;
    rtVal->applyTo(rt_analytic);
    rt_analytic.write();

    Info << "writing S for time " << runTime.timeName() << endl;
    S.write();

    Info << "writing qf for time " << runTime.timeName() << endl;
    rtVal->applyTo(rhof);
    rhof.write();
    
    Info << "writing T" << endl;
    tempVal->applyTo(T);
    T.write();
    
    Info << "writing P" << endl;
    PVal->applyTo(P);
    P.write();

    return EXIT_SUCCESS;
}
Esempio n. 11
0
/*
 * Send the requested file.
 */
static void sendtftp(struct testcase *test, struct formats *pf)
{
  int size;
  ssize_t n;
  sendblock = 1;
#if defined(HAVE_ALARM) && defined(SIGALRM)
  mysignal(SIGALRM, timer);
#endif
  sdp = r_init();
  sap = (struct tftphdr *)ackbuf;
  do {
    size = readit(test, &sdp, pf->f_convert);
    if (size < 0) {
      nak(ERRNO + 100);
      return;
    }
    sdp->th_opcode = htons((u_short)opcode_DATA);
    sdp->th_block = htons((u_short)sendblock);
    timeout = 0;
#ifdef HAVE_SIGSETJMP
    (void) sigsetjmp(timeoutbuf, 1);
#endif
    send_data:
    if (swrite(peer, sdp, size + 4) != size + 4) {
      logmsg("write");
      return;
    }
    read_ahead(test, pf->f_convert);
    for ( ; ; ) {
#ifdef HAVE_ALARM
      alarm(rexmtval);        /* read the ack */
#endif
      n = sread(peer, ackbuf, sizeof (ackbuf));
#ifdef HAVE_ALARM
      alarm(0);
#endif
      if (n < 0) {
        logmsg("read: fail");
        return;
      }
      sap->th_opcode = ntohs((u_short)sap->th_opcode);
      sap->th_block = ntohs((u_short)sap->th_block);

      if (sap->th_opcode == opcode_ERROR) {
        logmsg("got ERROR");
        return;
      }

      if (sap->th_opcode == opcode_ACK) {
        if (sap->th_block == sendblock) {
          break;
        }
        /* Re-synchronize with the other side */
        (void) synchnet(peer);
        if (sap->th_block == (sendblock-1)) {
          goto send_data;
        }
      }

    }
    sendblock++;
  } while (size == SEGSIZE);
}
Esempio n. 12
0
/*
 * Send the requested file.
 */
static void sendtftp(struct testcase *test, struct formats *pf)
{
  struct tftphdr *dp;
  struct tftphdr *ap;    /* ack packet */
  unsigned short block = 1;
  int size, n;
#if defined(HAVE_ALARM) && defined(SIGALRM)
  mysignal(SIGALRM, timer);
#endif
  dp = r_init();
  ap = (struct tftphdr *)ackbuf;
  do {
    size = readit(test, &dp, pf->f_convert);
    if (size < 0) {
      nak(errno + 100);
      return;
    }
    dp->th_opcode = htons((u_short)DATA);
    dp->th_block = htons((u_short)block);
    timeout = 0;
#ifdef HAVE_SIGSETJMP
    (void) sigsetjmp(timeoutbuf, 1);
#endif
    send_data:
    if (send(peer, dp, size + 4, 0) != size + 4) {
      logmsg("write\n");
      return;
    }
    read_ahead(test, pf->f_convert);
    for ( ; ; ) {
#ifdef HAVE_ALARM
      alarm(rexmtval);        /* read the ack */
#endif
      n = recv(peer, ackbuf, sizeof (ackbuf), 0);
#ifdef HAVE_ALARM
      alarm(0);
#endif
      if (n < 0) {
        logmsg("read: fail\n");
        return;
      }
      ap->th_opcode = ntohs((u_short)ap->th_opcode);
      ap->th_block = ntohs((u_short)ap->th_block);

      if (ap->th_opcode == ERROR) {
        logmsg("got ERROR");
        return;
      }

      if (ap->th_opcode == ACK) {
        if (ap->th_block == block) {
          break;
        }
        /* Re-synchronize with the other side */
        (void) synchnet(peer);
        if (ap->th_block == (block -1)) {
          goto send_data;
        }
      }

    }
    block++;
  } while (size == SEGSIZE);
}
Esempio n. 13
0
/*
 * Send the requested file.
 */
void
xmitfile(struct formats *pf)
{
	struct tftphdr *dp;
	struct tftphdr *ap;    /* ack packet */
	int size, n;
	volatile unsigned short block;

	signal(SIGALRM, timer);
	dp = r_init();
	ap = (struct tftphdr *)ackbuf;
	block = 1;
	do {
		size = readit(file, &dp, pf->f_convert);
		if (size < 0) {
			nak(errno + 100);
			goto abort;
		}
		dp->th_opcode = htons((u_short)DATA);
		dp->th_block = htons((u_short)block);
		timeouts = 0;
		(void)setjmp(timeoutbuf);

send_data:
		{
			int i, t = 1;
			for (i = 0; ; i++){
				if (send(peer, dp, size + 4, 0) != size + 4) {
					sleep(t);
					t = (t < 32) ? t<< 1 : t;
					if (i >= 12) {
						syslog(LOG_ERR, "write: %m");
						goto abort;
					}
				}
				break;
			}
		}
		read_ahead(file, pf->f_convert);
		for ( ; ; ) {
			alarm(rexmtval);        /* read the ack */
			n = recv(peer, ackbuf, sizeof (ackbuf), 0);
			alarm(0);
			if (n < 0) {
				syslog(LOG_ERR, "read: %m");
				goto abort;
			}
			ap->th_opcode = ntohs((u_short)ap->th_opcode);
			ap->th_block = ntohs((u_short)ap->th_block);

			if (ap->th_opcode == ERROR)
				goto abort;

			if (ap->th_opcode == ACK) {
				if (ap->th_block == block)
					break;
				/* Re-synchronize with the other side */
				(void) synchnet(peer);
				if (ap->th_block == (block -1))
					goto send_data;
			}

		}
		block++;
	} while (size == SEGSIZE);
abort:
	(void) fclose(file);
}
Esempio n. 14
0
int main (int argc, char *argv[]) {
	Uint32		prevTime;	/// Time of the previous frame time in milliseconds.
	Uint32		curTime;	/// Time of the current frame time in milliseconds.
	float		frameTime;	/// \ref curTime - \ref prevTime / 1000 (in seconds)
	SDL_Event	event;
	ac_input_t	prevInput;
	ac_input_t	curInput;
	bool		done;
	uint		frameCount = 0;
	uint		vertCount = 0;
	uint		triCount = 0;
	uint		dpCount = 0;
	uint		cpCount = 0;
	uint		frameCountTime;

	parse_args(argc, argv);

	// initialize SDL
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) {
		fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError());
		return 1;
	}

	// initialize renderer
	if (!r_init(&vertCount, &triCount, &dpCount, &cpCount)) {
		fprintf(stderr, "Unable to init renderer\n");
		return 1;
	}

	// initialize the system random number generator
	srand((uint)time(NULL));

	// set window caption to say that we're working
	SDL_WM_SetCaption("AC-130 - Generating resources, please wait...",
					"AC-130");

	// hide mouse cursor and grab input
	SDL_ShowCursor(0);
#ifdef NDEBUG
	SDL_WM_GrabInput(SDL_GRAB_ON);
#else
	bool grab = m_full_screen;
	SDL_WM_GrabInput(grab ? SDL_GRAB_ON : SDL_GRAB_OFF);
#endif // NDEBUG

	// make sure SDL cleans up before exit
	atexit(SDL_Quit);

	// clear out input structs
	memset(&prevInput, 0, sizeof(prevInput));
	memset(&curInput, 0, sizeof(curInput));

	// initialize game logic
	g_init();

	// update window caption to say that we're done generating stuff
	SDL_WM_SetCaption("AC-130", "AC-130");

	memset(&prevInput, 0, sizeof(prevInput));

	// initialize tick counter
	frameCountTime = SDL_GetTicks();
	// hardcode the first frame time at 20ms to get a bit more accurate results
	// of the FPS counter on the first FPS calculation
	prevTime = frameCountTime - 20;

#ifndef NDEBUG
	// grab the input in debug
	if (!grab) {
		SDL_WM_GrabInput(SDL_GRAB_ON);
		grab = true;
	}
#endif

	// program main loop
	done = false;
	while (!done) {
		curTime = SDL_GetTicks();
		frameTime = (float)(curTime - prevTime) * 0.001;
		prevTime = curTime;

		memset(&curInput, 0, sizeof(curInput));
		// copy buttons from last frame in case there was no MOUSEBUTTONUP event
		curInput.flags |= prevInput.flags
			& (INPUT_MOUSE_LEFT | INPUT_MOUSE_RIGHT);
		// dispatch events
		while (SDL_PollEvent(&event)) {
			switch (event.type) {
				// exit if the window is closed
				case SDL_QUIT:
					done = true;
					break;
				case SDL_KEYDOWN:
					switch (event.key.keysym.sym) {
						case SDLK_ESCAPE:
							done = true;
							break;
						case SDLK_f:
							curInput.flags |= INPUT_NEGATIVE;
							break;
						case SDLK_1:
							curInput.flags |= INPUT_1;
							break;
						case SDLK_2:
							curInput.flags |= INPUT_2;
							break;
						case SDLK_3:
							curInput.flags |= INPUT_3;
							break;
						case SDLK_p:
							curInput.flags |= INPUT_PAUSE;
							break;
#ifndef NDEBUG
						case SDLK_g:
							grab = !grab;
							if (grab) {
								SDL_WM_GrabInput(SDL_GRAB_ON);
								SDL_ShowCursor(0);
							} else {
								SDL_WM_GrabInput(SDL_GRAB_OFF);
								SDL_ShowCursor(1);
							}
							break;
#endif // NDEBUG
						default:	// shut up compiler
							break;
					}
					break;
				case SDL_MOUSEBUTTONDOWN:
				case SDL_MOUSEBUTTONUP:
					if (event.button.state == SDL_PRESSED)
						curInput.flags |= event.button.button == SDL_BUTTON_LEFT
							? INPUT_MOUSE_LEFT : INPUT_MOUSE_RIGHT;
					else
						curInput.flags &= event.button.button == SDL_BUTTON_LEFT
							? ~INPUT_MOUSE_LEFT : ~INPUT_MOUSE_RIGHT;
					break;
				case SDL_MOUSEMOTION:
					curInput.deltaX = event.motion.xrel;
					curInput.deltaY = event.motion.yrel;
					break;
			}
		}

		// show fps
		if (curTime - frameCountTime >= 2000) {
			float perFrameScale = 1.f / (float)frameCount;
			printf("%.0f FPS, %.0f tris/%.0f verts, "
					"%.0f/%.0f terrain patches culled (per frame)\n",
					(float)frameCount
						/ ((float)(curTime - frameCountTime) * 0.001),
					(float)triCount * perFrameScale,
					(float)vertCount * perFrameScale,
					(float)cpCount * perFrameScale,
					(float)(dpCount + cpCount) * perFrameScale);
			frameCountTime = curTime;
			frameCount = triCount = vertCount = dpCount = cpCount = 0;
		}

		g_frame(curTime, frameTime, &curInput);
		prevInput = curInput;
		frameCount++;

#if	0
		// bad performance simulation
		SDL_Delay(100);
#endif
	} // end main loop

	// show mouse cursor and release input
	SDL_ShowCursor(1);
	SDL_WM_GrabInput(SDL_GRAB_OFF);

	// shut all subsystems down
	r_shutdown();
	g_shutdown();

	return 0;
}
Esempio n. 15
0
/*
 * Send the requested file.
 */
static void sendtftp(struct testcase *test, struct formats *pf)
{
  int size;
  ssize_t n;
  /* These are volatile to live through a siglongjmp */
  volatile unsigned short sendblock; /* block count */
  struct tftphdr * volatile sdp = r_init(); /* data buffer */
  struct tftphdr * const sap = &ackbuf.hdr; /* ack buffer */

  sendblock = 1;
#if defined(HAVE_ALARM) && defined(SIGALRM)
  mysignal(SIGALRM, timer);
#endif
  do {
    size = readit(test, (struct tftphdr **)&sdp, pf->f_convert);
    if(size < 0) {
      nak(errno + 100);
      return;
    }
    sdp->th_opcode = htons((unsigned short)opcode_DATA);
    sdp->th_block = htons(sendblock);
    timeout = 0;
#ifdef HAVE_SIGSETJMP
    (void) sigsetjmp(timeoutbuf, 1);
#endif
    if(test->writedelay) {
      logmsg("Pausing %d seconds before %d bytes", test->writedelay,
             size);
      wait_ms(1000*test->writedelay);
    }

    send_data:
    if(swrite(peer, sdp, size + 4) != size + 4) {
      logmsg("write");
      return;
    }
    read_ahead(test, pf->f_convert);
    for(;;) {
#ifdef HAVE_ALARM
      alarm(rexmtval);        /* read the ack */
#endif
      n = sread(peer, &ackbuf.storage[0], sizeof(ackbuf.storage));
#ifdef HAVE_ALARM
      alarm(0);
#endif
      if(got_exit_signal)
        return;
      if(n < 0) {
        logmsg("read: fail");
        return;
      }
      sap->th_opcode = ntohs((unsigned short)sap->th_opcode);
      sap->th_block = ntohs(sap->th_block);

      if(sap->th_opcode == opcode_ERROR) {
        logmsg("got ERROR");
        return;
      }

      if(sap->th_opcode == opcode_ACK) {
        if(sap->th_block == sendblock) {
          break;
        }
        /* Re-synchronize with the other side */
        (void) synchnet(peer);
        if(sap->th_block == (sendblock-1)) {
          goto send_data;
        }
      }

    }
    sendblock++;
  } while(size == SEGSIZE);
}
Esempio n. 16
0
File: tftpd.c Progetto: 274914765/C
/*
 * Send the requested file.
 */
void send_file (struct formats *pf)
{
    struct tftphdr *dp, *r_init ();

    register struct tftphdr *ap;    /* ack packet */

    register int size, n;

    volatile int block;

    signal (SIGALRM, timer);
    dp = r_init ();
    ap = (struct tftphdr *) ackbuf;
    block = 1;
    do
    {
        size = readit (file, &dp, pf->f_convert);
        if (size < 0)
        {
            nak (errno + 100);
            goto abort;
        }
        dp->th_opcode = htons ((u_short) DATA);
        dp->th_block = htons ((u_short) block);
        timeout = 0;
        setjmp (timeoutbuf);

      send_data:
        if (send (peer, (const char *) dp, size + 4, 0) != size + 4)
        {
            syslog (LOG_ERR, "tftpd: write: %m\n");
            goto abort;
        }
        read_ahead (file, pf->f_convert);
        for (;;)
        {
            alarm (rexmtval);    /* read the ack */
            n = recv (peer, ackbuf, sizeof (ackbuf), 0);
            alarm (0);
            if (n < 0)
            {
                syslog (LOG_ERR, "tftpd: read: %m\n");
                goto abort;
            }
            ap->th_opcode = ntohs ((u_short) ap->th_opcode);
            ap->th_block = ntohs ((u_short) ap->th_block);

            if (ap->th_opcode == ERROR)
                goto abort;

            if (ap->th_opcode == ACK)
            {
                if ((u_short) ap->th_block == (u_short) block)
                    break;
                /* Re-synchronize with the other side */
                synchnet (peer);
                if ((u_short) ap->th_block == (u_short) (block - 1))
                    goto send_data;
            }

        }
        block++;
    }
    while (size == SEGSIZE);
  abort:
    fclose (file);
}
Esempio n. 17
0
/*
 * SDL_main
 * Program entry point.
 */
int SDL_main(int argc, char* argv[]){
	SDL_Event	event;
	SDL_Surface	*screen;

	if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0)
	{
		printf("Unable to initialize SDL: %s\n", SDL_GetError());
		return 1;
	}

	SDL_WM_SetCaption("Skybox Demo", "Skybox Demo");
	SDL_ShowCursor(SDL_DISABLE);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	screen = SDL_SetVideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, 32, SDL_OPENGL);
	if(!screen)
	{
		printf("Unable to set video mode: %s\n", SDL_GetError());
		return 1;
	}

	r_init();


	//Declaration of variables used in decoupling.
	int currTime = SDL_GetTicks();
	int prevTime = 0;

	//THIS IS THE GAME LOOP! *********************************************

	while(!user_exit)
	{
		//Set time counters to appropriate values for calculations.
		prevTime = currTime;
		currTime = SDL_GetTicks();

		//Handle input
		while(SDL_PollEvent(&event))
		{
			switch(event.type)
			{
			case SDL_KEYDOWN:
				input_keyDown(event.key.keysym.sym);
				break;
			case SDL_KEYUP:
				input_keyUp(event.key.keysym.sym);
				break;
			case SDL_MOUSEMOTION:
				input_mouseMove(event.motion.x, event.motion.y);
				break;
			case SDL_QUIT:
				user_exit = 1;
			}
		}

		input_update(currTime - prevTime);
		r_drawFrame();
	}

	//********************************************************************

	SDL_Quit();
	return 0;
}
int main(int argc, char *argv[])
{
  int step, ie, iside, i, j, k;
  double mflops, tmax, nelt_tot = 0.0;
  char Class;
  logical ifmortar = false, verified;

  double t2, trecs[t_last+1];
  char *t_names[t_last+1];

	//--------------------------------------------------------------------
	// Initialize NUMA control
	//--------------------------------------------------------------------
	numa_initialize_env(NUMA_MIGRATE_EXISTING);

  //---------------------------------------------------------------------
  // Read input file (if it exists), else take
  // defaults from parameters
  //---------------------------------------------------------------------
  FILE *fp;
  if ((fp = fopen("timer.flag", "r")) != NULL) {
    timeron = true;
    t_names[t_total] = "total";
    t_names[t_init] = "init";
    t_names[t_convect] = "convect";
    t_names[t_transfb_c] = "transfb_c";
    t_names[t_diffusion] = "diffusion";
    t_names[t_transf] = "transf";
    t_names[t_transfb] = "transfb";
    t_names[t_adaptation] = "adaptation";
    t_names[t_transf2] = "transf+b";
    t_names[t_add2] = "add2";
    fclose(fp);
  } else {
    timeron = false;
  }

  printf("\n\n NAS Parallel Benchmarks (NPB3.3-OMP-C) - UA Benchmark\n\n");

  if ((fp = fopen("inputua.data", "r")) != NULL) {
    int result;
    printf(" Reading from input file inputua.data\n");
    result = fscanf(fp, "%d", &fre);
    while (fgetc(fp) != '\n');
    result = fscanf(fp, "%d", &niter);
    while (fgetc(fp) != '\n');
    result = fscanf(fp, "%d", &nmxh);
    while (fgetc(fp) != '\n');
    result = fscanf(fp, "%lf", &alpha);
    Class = 'U';
    fclose(fp);
  } else {
    printf(" No input file inputua.data. Using compiled defaults\n");
    fre   = FRE_DEFAULT;
    niter = NITER_DEFAULT;
    nmxh  = NMXH_DEFAULT;
    alpha = ALPHA_DEFAULT;
    Class = CLASS_DEFAULT;
  }

  dlmin = pow(0.5, REFINE_MAX);
  dtime = 0.04*dlmin;

  printf(" Levels of refinement:        %8d\n", REFINE_MAX);
  printf(" Adaptation frequency:        %8d\n", fre);
  printf(" Time steps:                  %8d    dt: %15.6E\n", niter, dtime);
  printf(" CG iterations:               %8d\n", nmxh);
  printf(" Heat source radius:          %8.4f\n", alpha);
  printf(" Number of available threads: %8d\n", omp_get_max_threads());
  printf("\n");

  top_constants();

  for (i = 1; i <= t_last; i++) {
    timer_clear(i);
  }
  if (timeron) timer_start(t_init);

  // set up initial mesh (single element) and solution (all zero)
  create_initial_grid();

  r_init_omp((double *)ta1, ntot, 0.0);
  nr_init_omp((int *)sje, 4*6*nelt, -1);

  init_locks();

  // compute tables of coefficients and weights      
  coef();
  geom1();

  // compute the discrete laplacian operators
  setdef();

  // prepare for the preconditioner
  setpcmo_pre();

  // refine initial mesh and do some preliminary work
  time = 0.0;
  mortar();
  prepwork();
  adaptation(&ifmortar, 0);
  if (timeron) timer_stop(t_init);

  timer_clear(1);

  time = 0.0;
  for (step = 0; step <= niter; step++) {
    if (step == 1) {
      // reset the solution and start the timer, keep track of total no elms
      r_init((double *)ta1, ntot, 0.0);

      time = 0.0;
      nelt_tot = 0.0;
      for (i = 1; i <= t_last; i++) {
        if (i != t_init) timer_clear(i);
      }
      timer_start(1);
    }

    // advance the convection step 
    convect(ifmortar);

    if (timeron) timer_start(t_transf2);
    // prepare the intital guess for cg
    transf(tmort, (double *)ta1);

    // compute residual for diffusion term based on intital guess

    // compute the left hand side of equation, lapacian t
    #pragma omp parallel default(shared) private(ie,k,j,i) 
    {
    #pragma omp for
    for (ie = 0; ie < nelt; ie++) {
      laplacian(ta2[ie], ta1[ie], size_e[ie]);
    }

    // compute the residual 
    #pragma omp for
    for (ie = 0; ie < nelt; ie++) {
      for (k = 0; k < LX1; k++) {
        for (j = 0; j < LX1; j++) {
          for (i = 0; i < LX1; i++) {
            trhs[ie][k][j][i] = trhs[ie][k][j][i] - ta2[ie][k][j][i];
          }
        }
      }
    }
    } //end parallel

    // get the residual on mortar 
    transfb(rmor, (double *)trhs);
    if (timeron) timer_stop(t_transf2);

    // apply boundary condition: zero out the residual on domain boundaries

    // apply boundary conidtion to trhs
    #pragma omp parallel for default(shared) private(ie,iside)
    for (ie = 0; ie < nelt; ie++) {
      for (iside = 0; iside < NSIDES; iside++) {
        if (cbc[ie][iside] == 0) {
          facev(trhs[ie], iside, 0.0);
        }
      }
    }
    // apply boundary condition to rmor
    col2(rmor, tmmor, nmor);

    // call the conjugate gradient iterative solver
    diffusion(ifmortar);

    // add convection and diffusion
    if (timeron) timer_start(t_add2);
    add2((double *)ta1, (double *)t, ntot);
    if (timeron) timer_stop(t_add2);

    // perform mesh adaptation
    time = time + dtime;
    if ((step != 0) && (step/fre*fre == step)) {
      if (step != niter) {
        adaptation(&ifmortar, step);
      }
    } else {
      ifmortar = false;
    }
    nelt_tot = nelt_tot + (double)(nelt);
  }

  timer_stop(1);
  tmax = timer_read(1);

  verify(&Class, &verified);

  // compute millions of collocation points advanced per second.
  // diffusion: nmxh advancements, convection: 1 advancement
  mflops = nelt_tot*(double)(LX1*LX1*LX1*(nmxh+1))/(tmax*1.e6);

  print_results("UA", Class, REFINE_MAX, 0, 0, niter, 
                tmax, mflops, "    coll. point advanced", 
                verified, NPBVERSION, COMPILETIME, CS1, CS2, CS3, CS4, CS5, 
                CS6, "(none)");

  //---------------------------------------------------------------------
  // More timers
  //---------------------------------------------------------------------
  if (timeron) {
    for (i = 1; i <= t_last; i++) {
      trecs[i] = timer_read(i);
    }
    if (tmax == 0.0) tmax = 1.0;

    printf("  SECTION     Time (secs)\n");
    for (i = 1; i <= t_last; i++) {
      printf("  %-10s:%9.3f  (%6.2f%%)\n",
          t_names[i], trecs[i], trecs[i]*100./tmax);
      if (i == t_transfb_c) {
        t2 = trecs[t_convect] - trecs[t_transfb_c];
        printf("    --> %11s:%9.3f  (%6.2f%%)\n", 
            "sub-convect", t2, t2*100./tmax);
      } else if (i == t_transfb) {
        t2 = trecs[t_diffusion] - trecs[t_transf] - trecs[t_transfb];
        printf("    --> %11s:%9.3f  (%6.2f%%)\n", 
            "sub-diffuse", t2, t2*100./tmax);
      }
    }
  }

	//--------------------------------------------------------------------
	// Teardown NUMA control
	//--------------------------------------------------------------------
	numa_shutdown();

  return 0;
}
Esempio n. 19
0
/*
 * Send the requested file.
 */
int tftp_sendfile(int f, union sock_addr *peeraddr,
		   int fd, const char *name, const char *mode)
{
    struct tftphdr *ap;         /* data and ack packets */
    struct tftphdr *dp;
    int n;
    volatile int is_request;
    volatile u_short block;
    volatile int size, convert;
    volatile off_t amount;
    union sock_addr from;
    socklen_t fromlen;
    FILE *file;
    u_short ap_opcode, ap_block;

    startclock();               /* start stat's clock */
    dp = r_init();              /* reset fillbuf/read-ahead code */
    ap = (struct tftphdr *)ackbuf;
    convert = !strcmp(mode, "netascii");
    file = fdopen(fd, convert ? "rt" : "rb");
    block = 0;
    is_request = 1;             /* First packet is the actual WRQ */
    amount = 0;

    bsd_signal(SIGALRM, timer);
    do {
        if (is_request) {
            size = makerequest(WRQ, name, dp, mode) - 4;
        } else {
            /*      size = read(fd, dp->th_data, SEGSIZE);   */
            size = readit(file, &dp, convert);
            if (size < 0) {
                nak(f, peeraddr, errno + 100, NULL);
                break;
            }
            dp->th_opcode = htons((u_short) DATA);
            dp->th_block = htons((u_short) block);
        }
        timeout = 0;
        (void)sigsetjmp(timeoutbuf, 1);

        if (trace)
            tpacket("sent", dp, size + 4);
        n = sendto(f, dp, size + 4, 0,
                   &(peeraddr->sa), SOCKLEN(peeraddr));
        if (n != size + 4) {
            perror("tftp: sendto");
            goto abort;
        }
        read_ahead(file, convert);
        for (;;) {
            alarm(rexmtval);
            do {
                fromlen = sizeof(from);
                n = recvfrom(f, ackbuf, sizeof(ackbuf), 0,
                             &from.sa, &fromlen);
            } while (n <= 0);
            alarm(0);
            if (n < 0) {
                perror("tftp: recvfrom");
                goto abort;
            }
            sa_set_port(peeraddr, SOCKPORT(&from));  /* added */
            if (trace)
                tpacket("received", ap, n);
            /* should verify packet came from server */
            ap_opcode = ntohs((u_short) ap->th_opcode);
            ap_block = ntohs((u_short) ap->th_block);
            if (ap_opcode == ERROR) {
                printf("Error code %d: %s\n", ap_block, ap->th_msg);
                goto abort;
            }
            if (ap_opcode == ACK) {
                int j;

                if (ap_block == block) {
                    break;
                }
                /* On an error, try to synchronize
                 * both sides.
                 */
                j = synchnet(f);
                if (j && trace) {
                    printf("discarded %d packets\n", j);
                }
                /*
                 * RFC1129/RFC1350: We MUST NOT re-send the DATA
                 * packet in response to an invalid ACK.  Doing so
                 * would cause the Sorcerer's Apprentice bug.
                 */
            }
        }
        if (!is_request)
            amount += size;
        is_request = 0;
        block++;
    } while (size == SEGSIZE || block == 1);
  abort:
    fclose(file);
    stopclock();
    //if (amount > 0)
    //    printstats("Sent", amount);
    return amount;
}
Esempio n. 20
0
/*
 * Send the requested file.
 */
void
sendfile(int fd, char *name, char *mode)
{
	register struct tftphdr *ap;       /* data and ack packets */
	struct tftphdr *dp;
	volatile int block = 0, size = 0;
	int n;
	volatile unsigned long amount = 0;
	struct sockaddr_in from;
	socklen_t fromlen;
	volatile int convert;            /* true if doing nl->crlf conversion */
	FILE *file;

	startclock();           /* start stat's clock */
	dp = r_init();          /* reset fillbuf/read-ahead code */
	ap = (struct tftphdr *)ackbuf;
	file = fdopen(fd, "r");
	convert = !strcmp(mode, "netascii");

	signal(SIGALRM, timer);
	do {
		if (block == 0)
			size = makerequest(WRQ, name, dp, mode) - 4;
		else {
		/*      size = read(fd, dp->th_data, SEGSIZE);   */
			size = readit(file, &dp, convert);
			if (size < 0) {
				nak(errno + 100);
				break;
			}
			dp->th_opcode = htons((u_short)DATA);
			dp->th_block = htons((u_short)block);
		}
		timeout = 0;
		(void) sigsetjmp(timeoutbuf, 1);
send_data:
		if (trace)
			tpacket("sent", dp, size + 4);
		n = sendto(f, dp, size + 4, 0,
		    (struct sockaddr *)&s_inn, sizeof(s_inn));
		if (n != size + 4) {
			perror("tftp: sendto");
			goto abort;
		}
		read_ahead(file, convert);
		for ( ; ; ) {
			alarm(rexmtval);
			do {
				fromlen = sizeof (from);
				n = recvfrom(f, ackbuf, sizeof (ackbuf), 0,
				    (struct sockaddr *)&from, &fromlen);
			} while (n <= 0);
			alarm(0);
			if (n < 0) {
				perror("tftp: recvfrom");
				goto abort;
			}
			s_inn.sin_port = from.sin_port;   /* added */
			if (trace)
				tpacket("received", ap, n);
			/* should verify packet came from server */
			ap->th_opcode = ntohs(ap->th_opcode);
			ap->th_block = ntohs(ap->th_block);
			if (ap->th_opcode == ERROR) {
				printf("Error code %d: %s\n", ap->th_code,
					ap->th_msg);
				goto abort;
			}
			if (ap->th_opcode == ACK) {
				volatile int j = 0;

				if (ap->th_block == block) {
					break;
				}
				/* On an error, try to synchronize
				 * both sides.
				 */
				j = synchnet(f);
				if (j && trace) {
					printf("discarded %d packets\n",
							j);
				}
				if (ap->th_block == (block-1)) {
					goto send_data;
				}
			}
		}
		if (block > 0)
			amount += size;
		block++;
	} while (size == SEGSIZE || block == 1);
abort:
	fclose(file);
	stopclock();
	if (amount > 0)
		printstats("Sent", amount);
}