[solved] io.readLine() from serial takes forever
Hi there
I'm a OpenSesame and Python newbie who's running into timing problems.
The goal is, to continuously read from a serial device and present a different stimulus every 5 seconds.
After 5 stimuli or so, all the collected data is written to file.
This doesn't seem to be very complicated, however I get some odd delays which I can't really explain.
Here's my code:
--- Prepare-Tab:
(Imports and variable declaring is not interesting)
#Prepare Serial Port and IO-Wrapper
ser = serial.Serial(1)
sio = io.TextIOWrapper(io.BufferedRWPair(ser,ser,1), encoding='ascii')
data = ([])
numOfPictures = 5 # define the number of pictures. (15 available atm)
picsArr = [canvas(exp)]*numOfPictures # create array to hold canvas objects
def preparePics():
i=1
for i in range(0,numOfPictures): # i runs from 0 to 4
picture = 'bild ' + str(i+1)+ '.png' # therefor i+1
if not exp.file_in_pool(picture):
print('image "%s" not found', picture)
else:
path = exp.get_file(picture)
can = canvas(exp)
picsArr.append(can.image(path))
def showPic(index):
picsArr[index-1].show()
### a writeToFile() - function, not of interest here
--- Run-Tab
from openexp.canvas import canvas
#measuring time begins here
startTime = self.time()
#present each picture for 5s
endTime = startTime + numOfPictures * 5000
#prepare for main loop
index = 1
getPicture(1)
ser.flushInput()
#Main loop over timestamps
while (self.time() < endTime):
print "Before timeStamp update: " + str(self.time()) #PRINT 1
#update timestamp
timeStamp = self.time() - startTime - (index - 1)*5000
print "After timeStamp update: " + str(self.time()) #PRINT 2
#check if it's time to change the stimulus
if(timeStamp > 5000):
index += 1
showPic(index)
#try to read another line from Serial Device
print "Before readLine: " + str(self.time()) #PRINT 3
line = sio.readline()
print "After readLine, before sleep: " + str(self.time()) #PRINT 4
if not line:
self.sleep(1)
print "After sleep: " + str(self.time()) #PRINT 5
else:
#slice the line to x- and y-coordinates
i = line.find('/')
data.append([self.time() - startTime,index,line[:i-1],line[i+2:-1]])
print "After sleep/append: " + str(self.time()) #PRINT 6
ser.close()
writeToFile()
Between print 1,2 and 3 there's no delay at all. Between print 3 and 4 there's a delay of 100ms or more (which is really bad). Print 5 never gets execute, no idea why?! Between print 4 and 6 and between 6 and 1 (new loop) there's also no delay.
As you can see, line = sio.readline()
must be the culprit.
I could really need some help troubleshooting this. Is there something generally wrong about this aproach? Or is it a problem with the serial/io - libraries?
I appreciate any hints. :-)
Comments
Hi,
Interesting problem, and thanks a lot for the thorough explanation and investigation! I haven't actually used the
io
library much (only for buffering image streams), so I'm not quite familiar with it. I've tried looking your specific function up, but the docs aren't clear on whether there is a timeout in reading from a source like the Serial object.It seems like your code is simply waiting for something to become available to read, judging by the fact PRINT 5 never occurs. Could that be it?
Also, what is the Serial actually reading? Are they massive strings? Would it be an idea to specify a maximal line size, to prevent reading all of the built-up input at once? (Or, alternatively, to flush the input at the response window onset).
Am I making any sense to you at all, or am I misunderstanding your setup completely?
Thanks Edwin for your thoughts on this.
Your understanding of the setup is quite correct. We have a plate which measures the balance of a person standing on it (similar to a Wii-board). It sends the coordinates every 100ms through a COM port in a string of 10 characters or so. So there's 10 times per second a very short string, what leads to the assumption that the data itself shouldn't be a problem. I also watched the ressources of the system while running an experiment and the RAM usage is only rising some few megabytes, the CPU isn't fully loaded either.
It just came to my mind that the line-variable should be deleted after each readline, that's probably why the PRINT 5 is never executed.
What do you think about the design of the code? I first considered usage of multi-threading, with one thread reading the io-stream. But then I read a reply of yours on a similar question in the forum, suggesting this linear approach using an infinte while-loop. Can this approach even be accurate enought? By accurate I mean a standard error of maybe 5ms.
Ok here's a little update.
Indeed, the problem is that io.readline() seems to take a timeout until a EOF is read.
This means that the
if not line ...
in my while-loop is useless, since the loop "sleeps" until a complete line is found.I would highly appreciate some good practices using pyserial. I'm just not sure if the current design is reliable enough...
However, I also have a problem using the list containing self.offline_canvas() - objects.
The following code only presents a black screen. What's wrong in
preparePics()
?The path should be ok, the previous version where
canvas(exp).show()
was used ran flawlessly.My tip would be to avoid the
io
module (I don't know it, but it doesn't seem necessary here) and just use the pyserial API directly:I don't think there are any 'magic tricks', everything is pretty much documented on the pyserial site. In general terms, you will need to read data from the serial port and make sure that it's segmented in the right way. How you do this depends on the specifics of the device that you're communicating with. Maybe the vendor has some examples? If not, I would start by creating a short standalone Python script that does this. Once you have that, you can easily integrate it into your experiment.
In this code snippet, there is no call to
showPic()
. In other words, if this is the entire script (?), nothing is shown. If that's not it, you could try to do some more debugging, for example by printing outpath
(is it correct?) and drawing other things to thecanvas
objects so that you know for sure when it is presented.Check out SigmundAI.eu for our OpenSesame AI assistant!
Thanks for your fast reply, I was just checking the post to delete the second part. It's a really cheap mistake, of course the preparePics()-function is never called. :@)
So everything is fine with the canvas objects.
I will give your tip a try and throw out the
io
-module.Hey Sebastiaan, I just realized this ticket is still open.
The pyserial module did the trick for me, this problem can be marked als [solved]. :-)