libftdi Archives

Subject: Re: use timeout on read

From: Ladislav Vaiz <spam@xxxxxxxxx>
To: libftdi@xxxxxxxxxxxxxxxxxxxxxxx
Date: Fri, 27 Mar 2009 15:29:11 +0100
Jonatan Magnusson napsal(a):
fre 2009-03-27 klockan 13:58 +0100 skrev Ladislav Vaiz:

  
Hi Jonatan,
I use my own wrapper around ftdi_read_data. It returns immediately when 
error occur or any amount of data is read. Timeout should be measured 
with good precision.
Lada

int my_ftdi_read(struct sconn *sconn, void *data, size_t len, int 
timeout_ms){
    int ret;
    struct timeval start, stop;
    int usec, sec;

    gettimeofday(&start, NULL);
    while(1){
        ret = ftdi_read_data(sconn->ftdi, data, len);
        if (ret) break;
        gettimeofday(&stop, NULL);
        usec = stop.tv_usec - start.tv_usec;
        sec = stop.tv_sec - start.tv_sec;
        if (usec<0) usec+=1000000,sec--;
        if (sec>timeout_ms/1000) break;
        if (usec/1000>timeout_ms) break;
        usleep(1000);
    }
    return ret;
}


    


Hi,

That consumes a little more CPU than I was hoping for, but I will do
something similar.
  

You can increase sleep argument but you will loose precision.

Btw, what are you doing with usec there? I don't think your code will
work with a timeout of 1200 ms for example: usec will never reach
12000000, so it will exit when sec > timeout_ms/1000, that is after 2
seconds.
  

You're right. I've used it only for shorter timeouts. Should be:
        if (usec/1000 > timeout_ms % 1000) break;


I do it like this:

	...
	gettimeofday (&stop, NULL);
	ms = (stop.tv_usec - start.tv_usec) / 1000;
	ms += (stop.tv_sec - start.tv_sec) * 1000;
	if (ms > timeout_ms)
		break;
	...
  

OK, It's possible.

Oh, I didn't know about that comma-separated list of expressions syntax
you're using (usec+=1000000,sec--), nice!
  

It's same as
if (usec<0) {usec+=1000000;sec--;}
http://en.wikipedia.org/wiki/Comma_operator


Lada


libftdi - see http://www.intra2net.com/en/developer/libftdi for details.
To unsubscribe send a mail to libftdi+unsubscribe@xxxxxxxxxxxxxxxxxxxxxxx


Current Thread