views:

840

answers:

5

Hi!

We're trying to read data from 2 usb mice connected to a linux box (this data is used for odometry/localization on a robot). So we need to continuously read from each mouse how much it moved. The problem is that when a mouse is not moving, it doesn't send any data, so the file stream from which we get the data blocks execution and therefore the program can't do the odometry calculations (which involve time measurement for speed).

Is there a way to set a timeout on the input stream (we're using ifstream in C++ and read from /dev/input/mouse), so that we're able to know when the mouse doesn't move, instead of waiting for an event to be received? Or do we need to mess up with threads (arggh...)? Any other suggestions are welcome!

Thanks in advance!

A: 

No, there is no such method. You'll have to wait for an event, or create a custom Timer class and wait for a timeout to repoll, or use threads.

dirkgently
+1  A: 

What you're looking for would be an asynchronous way to read from ifstream, like socket communication. The only thing that could help would be the readsome function, perhaps it returns if no data is available, but I doubt this helps.

Using threads would be the best way to handle this.

schnaader
A: 

Clearly, the right way to go here is to use blocking calls to retrieve data from both mice. Use threads to synchronize the whole thing. I believe there is a pretty simple way to do that.

Use one thread for each blocking input call. When receiving data from either one, add a corresponding item in a thread-safe queue. That's all these threads should be used for.

Use one thread to deal with received data. It will essentially be a blocking call to "pop" the first available item in the queue. Now you can do whatever you want to do when receiving data from one mouse !

Benoît
+4  A: 
Marc
+1, select() is the way to go since it avoids the headaches caused by multithreading.
Adam Rosenfield
A: 

Take a look at the boost Asio library. This might help you deal with the threading suggested by schnaeder.

Pontus Gagge