Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PySerial: how to understand that the timeout occured while reading from serial port?

I'm using PySerial to read from serial port like in the code below. CheckReadUntil() read output of the command that I send to serial port until the sequence of symbols readUntil are in the serial output.

...

self.ser = serial.Serial(comDev, 115200, timeout=10)

...

#Function that continue to read from Serial port until 'readUntil' 
#sequence of symbols appears
def CheckReadUntil(self, readUntil):
    outputCharacters = []
    while 1:
        ch = self.ser.read()
        outputCharacters += ch
        if outputCharacters[-len(readUntil):]==readUntil:
            break
    outputLines = ''.join(outputCharacters)
    return outputLines

However, if there is no sequence readUntil (for any reason), I'm just stuck in the function CheckReadUntil() forever. The setting timeout=10 sets up timeout so I'm stuck in a loop that iterates every 10 seconds and does nothing, just waiting.

How it is possible to understand that there was a timeout event so I may exit the infinite loop? Output length may be different.

like image 606
Konstantin Avatar asked Mar 24 '14 09:03

Konstantin


People also ask

What does timeout mean in pySerial?

timeout = None : wait forever / until requested number of bytes are received. timeout = 0 : non-blocking mode, return immediately in any case, returning zero or more, up to the requested number of bytes.

How do you check if you have pySerial?

To check that it is installed, start Pyzo and at the command prompt type in: import serial If it just gives you another >>> prompt, all is good. Checking that it is really working.

Is pySerial read blocked?

Totally non-blocking.

Is pySerial the same as serial?

PySerial is a library which provides support for serial connections ("RS-232") over a variety of different devices: old-style serial ports, Bluetooth dongles, infra-red ports, and so on.


1 Answers

UPDATE (previous answer was not correct, this is the working code from @konstantin):

...

self.ser = serial.Serial(comDev, 115200, timeout=10)

...

#Function that continue to read from Serial port until 'readUntil' 
#sequence of symbols appears
def CheckReadUntil(self, readUntil):
    outputCharacters = []
    while 1:
        ch = self.ser.read()
        if len(ch) == 0:
            break
        outputCharacters += ch
        if outputCharacters[-len(readUntil):]==readUntil:
            break
    outputLines = ''.join(outputCharacters)
    return outputLines
like image 140
Fookatchu Avatar answered Oct 03 '22 12:10

Fookatchu