Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Supported by

[solved] io.readLine() from serial takes forever

edited February 2016 in OpenSesame

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

  • edited 5:18PM

    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? :p

  • edited 5:18PM

    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.

  • edited 5:18PM

    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.


    numOfPictures = 5 # define the number of pictures. (15 available atm) picsArr = [self.offline_canvas() for _ in range(numOfPictures)] def preparePics(): for i in range(numOfPictures): # i runs from 0 to 4 picsArr[i] = self.offline_canvas() # should be of no effect picture = 'bild ' + str(i)+ '.png' if not exp.file_in_pool(picture): print('image "%s" not found', picture) else: path = exp.get_file(picture) print(path) picsArr[i].image(path) def showPic(index): picsArr[index].show()
  • edited 5:18PM

    I would highly appreciate some good practices using pyserial. I'm just not sure if the current design is reliable enough...

    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.

    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.

    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 out path (is it correct?) and drawing other things to the canvas objects so that you know for sure when it is presented.

  • edited 5:18PM

    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.

  • edited 5:18PM

    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]. :-)

Sign In or Register to comment.

agen judi bola , sportbook, casino, togel, number game, singapore, tangkas, basket, slot, poker, dominoqq, agen bola. Semua permainan bisa dimainkan hanya dengan 1 ID. minimal deposit 50.000 ,- bonus cashback hingga 10% , diskon togel hingga 66% bisa bermain di android dan IOS kapanpun dan dimana pun. poker , bandarq , aduq, domino qq , dominobet. Semua permainan bisa dimainkan hanya dengan 1 ID. minimal deposit 10.000 ,- bonus turnover 0.5% dan bonus referral 20%. Bonus - bonus yang dihadirkan bisa terbilang cukup tinggi dan memuaskan, anda hanya perlu memasang pada situs yang memberikan bursa pasaran terbaik yaitu http://45.77.173.118/ Bola168. Situs penyedia segala jenis permainan poker online kini semakin banyak ditemukan di Internet, salah satunya TahunQQ merupakan situs Agen Judi Domino66 Dan BandarQ Terpercaya yang mampu memberikan banyak provit bagi bettornya. Permainan Yang Di Sediakan Dewi365 Juga sangat banyak Dan menarik dan Peluang untuk memenangkan Taruhan Judi online ini juga sangat mudah . Mainkan Segera Taruhan Sportbook anda bersama Agen Judi Bola Bersama Dewi365 Kemenangan Anda Berapa pun akan Terbayarkan. Tersedia 9 macam permainan seru yang bisa kamu mainkan hanya di dalam 1 ID saja. Permainan seru yang tersedia seperti Poker, Domino QQ Dan juga BandarQ Online. Semuanya tersedia lengkap hanya di ABGQQ. Situs ABGQQ sangat mudah dimenangkan, kamu juga akan mendapatkan mega bonus dan setiap pemain berhak mendapatkan cashback mingguan. ABGQQ juga telah diakui sebagai Bandar Domino Online yang menjamin sistem FAIR PLAY disetiap permainan yang bisa dimainkan dengan deposit minimal hanya Rp.25.000. DEWI365 adalah Bandar Judi Bola Terpercaya & resmi dan terpercaya di indonesia. Situs judi bola ini menyediakan fasilitas bagi anda untuk dapat bermain memainkan permainan judi bola. Didalam situs ini memiliki berbagai permainan taruhan bola terlengkap seperti Sbobet, yang membuat DEWI365 menjadi situs judi bola terbaik dan terpercaya di Indonesia. Tentunya sebagai situs yang bertugas sebagai Bandar Poker Online pastinya akan berusaha untuk menjaga semua informasi dan keamanan yang terdapat di POKERQQ13. Kotakqq adalah situs Judi Poker Online Terpercayayang menyediakan 9 jenis permainan sakong online, dominoqq, domino99, bandarq, bandar ceme, aduq, poker online, bandar poker, balak66, perang baccarat, dan capsa susun. Dengan minimal deposit withdraw 15.000 Anda sudah bisa memainkan semua permaina pkv games di situs kami. Jackpot besar,Win rate tinggi, Fair play, PKV Games